package com.atlassian.stash.internal.johnson;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.event.api.EventListener;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.johnson.event.AddEvent;
import com.atlassian.plugin.PluginAccessor;
import com.atlassian.plugin.event.events.PluginFrameworkStartedEvent;
import com.atlassian.stash.internal.ApplicationSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Listens for plugin events which should be translated into Johnson events and publishes {@link AddEvent}s wrapping
 * them, which will trigger their addition to the Johnson event container.
 * <p>
 * This component will automatically be detected by the {@code EventListenerRegistrar} and registered with the
 * {@code EventPublisher}.
 */
@Component("johnsonPluginEventListener")
public class JohnsonPluginEventListener extends BaseJohnsoningPluginEventListener {

    private final ApplicationSettings applicationSettings;

    @Autowired
    public JohnsonPluginEventListener(EventPublisher eventPublisher, I18nService i18nService, ApplicationSettings applicationSettings) {
        super(eventPublisher, i18nService);
        this.applicationSettings = applicationSettings;
    }

    /**
     * Listens for {@code PluginFrameworkStartedEvent} and creates a Johnson event indicating all required plugins that have failed.
     *
     * @param event plugin framework started event
     */
    @EventListener
    public void onPluginFrameworkStarted(PluginFrameworkStartedEvent event) {
        PluginAccessor pluginAccessor = event.getPluginAccessor();
        for (String key : applicationSettings.getRequiredPluginKeys()) {
            enabledOrRiot(key, pluginAccessor.getPlugin(key));
        }
    }
}
