package com.atlassian.stash.internal.lifecycle;

import com.atlassian.johnson.spring.lifecycle.LifecycleUtils;
import com.atlassian.bitbucket.Product;
import com.atlassian.bitbucket.util.Progress;
import com.atlassian.bitbucket.util.ProgressImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import javax.servlet.ServletContext;

/**
 * @since 3.2
 */
public class DefaultStartupManager implements StartupManager {

    private static final Logger log = LoggerFactory.getLogger(DefaultStartupManager.class);

    private final ServletContext servletContext;

    private volatile Progress progress;

    public DefaultStartupManager(ServletContext servletContext) {
        this.servletContext = servletContext;

        progress = new ProgressImpl("Starting " + Product.FULL_NAME, 0);
    }

    @Nonnull
    @Override
    public Progress getProgress() {
        return progress;
    }

    @Override
    public boolean isStarting() {
        return LifecycleUtils.isStarting(servletContext);
    }

    @Override
    public void onProgress(@Nonnull Progress progress) {
        Progress oldProgress = this.progress;
        if (progress.getPercentage() < oldProgress.getPercentage()) {
            log.debug("Progress going backwards: {} {}% -> {} {}%!", oldProgress.getMessage(),
                    oldProgress.getPercentage(), progress.getMessage(), progress.getPercentage());
        }
        this.progress = progress;
    }
}
