package org.jasig.cas.client.session;

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

import com.house365.rest.context.ServiceConstant;
import org.jasig.cas.client.session.SessionMappingStorage;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 系统创建session事件监听 〈功能详细描述〉
 */
public class SessionListener implements HttpSessionListener {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger("InterfaceLog");

    private SessionMappingStorage sessionMappingStorage;

    public void sessionCreated(final HttpSessionEvent event) {
        // 设置默认城市为NJ,默认用户为admin
        //event.getSession().setAttribute(ServiceConstant.USER_NAME, "admin");
        event.getSession().setAttribute(ServiceConstant.CITY_ID, "nj");
        event.getSession().setAttribute("city", "nj");
        LOGGER.debug("session创建成功");
    }

    public void sessionDestroyed(final HttpSessionEvent event) {
        LOGGER.info("SessionListener sessionDestroyed");
        if (sessionMappingStorage == null) {
            sessionMappingStorage = getSessionMappingStorage();
        }
        final HttpSession session = event.getSession();
        sessionMappingStorage.removeBySessionById(session.getId());
    }

    /**
     * Obtains a {@link SessionMappingStorage} object. Assumes this method will always return the same
     * instance of the object.  It assumes this because it generally lazily calls the method.
     *
     * @return the SessionMappingStorage
     */
    protected static SessionMappingStorage getSessionMappingStorage() {
        return SingleSignOutFilter.getSingleSignOutHandler().getSessionMappingStorage();
    }

}
