package ru.yandex.qe.jetty.server;

import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.SmartLifecycle;

public class JettyRunner implements SmartLifecycle {

    private static final Logger LOG = LoggerFactory.getLogger(JettyRunner.class);

    private Server server;

    boolean enable;

    @Required
    public void setServer(Server server) {
        this.server = server;
    }

    @Required
    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    @Override
    public void start() {
        if (!enable) {
            LOG.warn("JettyRunner is not enabled; not starting");
            return;
        }
        try {
            server.start();
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new Error(e.getMessage(), e);
        }
    }

    @Override
    public void stop() {
        try {
            server.stop();
        } catch (Exception e) {
            LOG.warn("Ignored exception", e);
            // ignore error
        }
    }

    @Override
    public boolean isAutoStartup() {
        return false;
    }

    @Override
    public void stop(final Runnable callback) {
        stop();
        callback.run();
    }

    @Override
    public boolean isRunning() {
        return server.isRunning();
    }

    @Override
    public int getPhase() {
        return Integer.MAX_VALUE;
    }
}
