package gov.va.med.authentication.kernel;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;
import org.apache.log4j.Level;

/**
 * This class is used to listen for an event that signals that the session of an actively loggeed in
 * user is ending. If so, it calls logout actions. Configure in web.xml as follows:
 * <pre>
 * &lt;listener&gt;
 *   &lt;listener-class&gt;
 *     gov.va.med.authentication.kernel.KaajeeHttpSessionListener
 *   &lt;/listener-class&gt;
 * &lt;/listener&gt;
 * </pre>
 * @author VHIT Security and Other Common Services (S&OCS)
 * @version 1.1.0.007
 */
public class KaajeeHttpSessionListener implements HttpSessionListener {

	private static final Logger LOGGER = Logger.getLogger(KaajeeHttpSessionListener.class);

	/**
	 * No actions implemented at session creation.
	 * @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
	 */
	public void sessionCreated(HttpSessionEvent event) {
	}

	/**
	 * When session ends, call logout actions, if we can get the LoginUserInfoVO object (signifying a logout
	 * of a user that was logged in.) Appears to be container-specific whether this action is called;
	 * we double-cover this with KaajeeSessionAttributeListener looking for this attribute to be removed, as well.
	 * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
	 */
	public void sessionDestroyed(HttpSessionEvent event) {
		if (LOGGER.isEnabledFor(Level.DEBUG)) {
			LOGGER.debug("Session destroyed " + event.getSession().getId());
		}
		LoginUserInfoVO userInfo = (LoginUserInfoVO) event.getSession().getAttribute(LoginUserInfoVO.SESSION_KEY);
		if (userInfo != null) {
			if (LOGGER.isEnabledFor(Level.DEBUG)) {
				LOGGER.debug("Got LoginUserInfoVO object.");
			}
			LogoutController.performLogoutActions(userInfo.getSignonLogIen(), userInfo.getUserDuz(), userInfo.getLoginStationNumber());

		} else {
			if (LOGGER.isEnabledFor(Level.DEBUG)) {
				LOGGER.debug("Did not find LoginUserInfoVO object.");
			}
		}
	}

}
