package gov.va.med.esr.ui.common.action;

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

import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.web.context.WebApplicationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import gov.va.med.fw.ui.DelegatingActionUtils;
import gov.va.med.esr.ui.ApplicationConstants;
import gov.va.med.esr.service.PersonMergeService;
import gov.va.med.fw.model.EntityKey;
import gov.va.med.esr.common.model.person.PersonMergeInfo;
import gov.va.med.fw.service.ServiceException;

/**
 * A session destroy listener to cleanup before the session is destroyed.
 *
 * @author DNS   CHENB
 * @author Andrew Pach
 */
public class SessionDestroyListener extends ApplicationObjectSupport implements HttpSessionListener
{
    private static final String PERSON_MERGE_SERVICE = "personMergeService";
	protected Log logger = LogFactory.getLog(getClass());

    /**
     * Default constructor.
     */
	public SessionDestroyListener()
    {
        super();
    }

	public void	sessionCreated(HttpSessionEvent	se)
    {
	}

    public void sessionDestroyed(HttpSessionEvent se)
    {
        // Get the session for this user
        HttpSession session = se.getSession();

        EntityKey key = (EntityKey)session.getAttribute(ApplicationConstants.SessionData.LOCKED_MERGE_INFO_ENTITYKEY);
		if (key != null)
		{
            try
            {
                if (logger.isDebugEnabled())
                {
                    logger.debug("Unlocking person merge (from sessionDestroyed) record with ID " +
                        key.getKeyValueAsString() + " on session " + session.getId() +
                        " and lock key removed from session.");
                }

                // Remove the key from session
                session.setAttribute(ApplicationConstants.SessionData.LOCKED_MERGE_INFO_ENTITYKEY, null);

                // Get the person merge service
                PersonMergeService mergeService = getPersonMergeService(session);

                // Get the person merge info associated with the key
                PersonMergeInfo info = mergeService.getPersonMergeInfo(key);
				if (info != null)
				{
                    // Unlock the record
                    info.setRecordLocked(Boolean.FALSE);
					mergeService.updatePersonMergeInfo(info);
				}
			}
            catch (ServiceException ex)
            {
	            logger.error("Error to unlock PersonMergeInfo for key: " + key, ex);
			}
		}
	}

    public PersonMergeService getPersonMergeService(HttpSession session)
    {
        WebApplicationContext appContext =
            DelegatingActionUtils.findRequiredWebApplicationContext( session.getServletContext());
        return (PersonMergeService)appContext.getBean(PERSON_MERGE_SERVICE, PersonMergeService.class);
    }
}
