package com.atlassian.stash.internal.config;

import com.atlassian.config.lifecycle.events.ApplicationStartedEvent;
import com.atlassian.config.lifecycle.events.ApplicationStoppedEvent;
import com.atlassian.config.lifecycle.events.ApplicationStoppingEvent;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.stash.internal.ApplicationConstants;
import com.atlassian.stash.internal.spring.AbstractSmartLifecycle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Long-term Atlassian Config should be fully removed. However, the analytics plugin depends on it and appears
 * to expect its events to be raised in order to run correctly.
 * <p>
 * Note: Atlassian Config is compiled against Atlassian Johnson 1.0, so {@code DefaultLifecycleManager} cannot
 * be used in Stash.
 *
 * @since 3.2
 */
@Component
public class ConfigLifecycle extends AbstractSmartLifecycle {

    private final EventPublisher eventPublisher;

    @Autowired
    public ConfigLifecycle(EventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    @Override
    public int getPhase() {
        return ApplicationConstants.LIFECYCLE_PHASE_CONFIG;
    }

    @Override
    public void start() {
        eventPublisher.publish(new ApplicationStartedEvent(this));

        super.start();
    }

    @Override
    public void stop() {
        eventPublisher.publish(new ApplicationStoppingEvent(this));
        eventPublisher.publish(new ApplicationStoppedEvent(this));

        super.stop();
    }
}
