package com.atlassian.bitbucket.installer.scripts;

import com.atlassian.bitbucket.Product;
import com.atlassian.bitbucket.installer.InstallerConstants;
import com.atlassian.bitbucket.installer.utils.InstallerUtils;
import com.atlassian.inception.TomcatChecker;
import com.install4j.api.context.InstallerContext;

import java.util.concurrent.TimeUnit;

/**
 * This is the screen to show the Launching progress to the user.
 */
public class DisplayProgressScreen extends AbstractInstallerScript {

    private static final int WAIT_INTERVAL_IN_MILISECOND = 10000;

    public DisplayProgressScreen(InstallerContext context, InstallerUtils utils) {
        super(context, utils);
    }

    /**
     * Wait for Bitbucket to start up. This method will try to establish a connection with Tomcat's control port
     * to assess if Bitbucket is running. After a configured timeout
     * (see compiler variable {@link InstallerConstants#KEY_APP_STARTUP_TIMEOUT}) this method will bail out.
     *
     * @return {@code true} if the connection to tomcat's control port was established withing the timeout. {@code false} otherwise
     * @throws InterruptedException
     */
    public boolean checkIfAppRunning() throws InterruptedException {

        int shutdownPort = getInstallationDetails().getControlPort();
        long waitSecond = TimeUnit.SECONDS.toMillis(Long.parseLong(getContext()
                .getCompilerVariable(InstallerConstants.KEY_APP_STARTUP_TIMEOUT)));

        getUtils().logInfo(String.format("The waitSecond is %d for %s launcher.", waitSecond, Product.NAME));

        // Give the application some time to start
        boolean isRunning = false;
        for (int i = 0; !isRunning && i < waitSecond / WAIT_INTERVAL_IN_MILISECOND; i++) {
            getUtils().logInfo(String.format("Waiting for %s to start up.", Product.NAME));

            Thread.sleep(WAIT_INTERVAL_IN_MILISECOND);
            isRunning = TomcatChecker.isTomcatRunning(shutdownPort);
        }

        getContext().setVariable(InstallerConstants.KEY_APP_LAUNCH_ERROR, !isRunning);
        return isRunning;
    }
}
