package no.valg.valgnatt.mottak;

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

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

public class MottakServletContextListener implements ServletContextListener {

    private static final int DESTROY_TIMEOUT = 60000; // Milliseconds

    private MainMottak mainMottak;
    private Thread t;

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

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        mainMottak.shutdown();
        t.interrupt();
        try {
            t.join(DESTROY_TIMEOUT);
        } catch (InterruptedException e) {
            // Ignore
        }
    }

}
