package gov.va.med.authentication.kernel;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

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

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

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

	/**
	 * No actions taken.
	 * @see javax.servlet.http.HttpSessionAttributeListener#attributeAdded(javax.servlet.http.HttpSessionBindingEvent)
	 */
	public void attributeAdded(HttpSessionBindingEvent event) {
	}

	/**
	 * Look for LoginUserInfoVO being deleted from session. If so this signals a logout, in which case
	 * specific logout actions are performed. Appears to be container-specific whether this action is called;
	 * we double-cover this with KaajeeHttpSessionListener looking for the session to terminate as well.
	 * @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent)
	 **/
	public void attributeRemoved(HttpSessionBindingEvent event) {
		if (event.getName().equals(LoginUserInfoVO.SESSION_KEY)) {
			if (LOGGER.isEnabledFor(Level.DEBUG)) {
				LOGGER.debug("Attribute removed: " + event.getName());
			}
			LoginUserInfoVO userInfo = (LoginUserInfoVO) event.getValue();
			if (userInfo != null) {
				if (LOGGER.isEnabledFor(Level.DEBUG)) {
					LOGGER.debug("Found LoginUserInfoVO object.");
				}
				LogoutController.performLogoutActions(userInfo.getSignonLogIen(), userInfo.getUserDuz(), userInfo.getLoginStationNumber());
			} else {
				if (LOGGER.isEnabledFor(Level.DEBUG)) {
					LOGGER.debug("Did not find LoginUserInfoVO value.");
				}
			}
		}
	}

	/**
	 * no actions taken.
	 * @see javax.servlet.http.HttpSessionAttributeListener#attributeReplaced(javax.servlet.http.HttpSessionBindingEvent)
	 */
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		//
	}

}
