package no.valg.valgnatt.backend;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.support.WebApplicationContextUtils;

public class BackendServletContextListener implements ServletContextListener {

    private static final int DESTROY_TIMEOUT = 60000; // Milliseconds

    private MainBackend mainBackend;
    private Thread t;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        mainBackend = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContextEvent.getServletContext()).getBean(MainBackend.class);
        t = new Thread(mainBackend, "MainBackend");
        t.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        mainBackend.setØnsketKjøreTilstand(MainBackend.KjøreTilstand.STOPP);
        mainBackend.stoppUtsendelseAvRapporter();
        t.interrupt();
        try {
            t.join(DESTROY_TIMEOUT);
        } catch (InterruptedException e) {
            // Ignore
        }
    }

}
