package com.dla.dda.system.servlets;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

import com.dla.dda.utils.spring.BeanProvider;;

/**
 * @see Se agrega esta clase utilitaria debido a que tomcat presenta un issue al
 *      hacer shutdown al contenedor de JMS (Solo usar cuando este emmebido el
 *      contenedor)
 * @author montieln
 *
 */
@WebListener
public class JMSContainerShutDownHook implements ServletContextListener {

	private static Logger logger = LoggerFactory.getLogger(JMSContainerShutDownHook.class);

	@Override
	public void contextDestroyed(ServletContextEvent context) {

		logger.info("Destroying context.. [{}]", context);

		try {
			DefaultMessageListenerContainer container = BeanProvider.getBean("jmsContainer",
					DefaultMessageListenerContainer.class);

			container.shutdown();

			Thread.sleep(3000);

			logger.info("JMS Context destroyed");

		} catch (Exception e) {
			logger.error("Error on shutting down JMS Context [{}]", e.getMessage(), e);
		}

	}

	@Override
	public void contextInitialized(ServletContextEvent context) {
		logger.info("Initializing context.. [{}]", context);

	}

}
