package cn.com.qmth.stmms.common.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.com.qmth.stmms.common.session.model.StmmsSession;
import cn.com.qmth.stmms.common.session.service.SessionService;
import cn.com.qmth.stmms.common.utils.RequestUtils;

/**
 * 对每次动态页面的请求时，更新会话cookie的有效期
 */
public class SessionFilter extends HttpServlet implements Filter {

    private Set<String> excludeURIs;

    private static final long serialVersionUID = -6516046520244652987L;

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String contextPath = request.getContextPath();
        String uri = request.getRequestURI();
        // 去掉contextpath
        if (!contextPath.equals("/") && StringUtils.isNotEmpty(contextPath)) {
            int i = uri.indexOf('/', 2);
            uri = uri.substring(i, uri.length());
        }
        RequestUtils.setURI(request, uri);

        if (!isExcludeURIPrefix(uri)) {
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request
                    .getSession().getServletContext());
            SessionService sessionService = (SessionService) webApplicationContext.getBean("sessionService");
            StmmsSession session = sessionService.get(request);
            RequestUtils.setSession(request, sessionService.get(request));
            for (Entry<String, String> entry : session.getParameters()) {
                request.setAttribute(entry.getKey(), entry.getValue());
            }
            filterChain.doFilter(request, response);
            // try {
            // filterChain.doFilter(request, response);
            // } catch (Exception e) {
            // } finally {
            // sessionService.put(request, response,
            // RequestUtils.getSession(request));
            // }
        } else {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        excludeURIs = new HashSet<String>();
        String value = filterConfig.getInitParameter("excludeURI");
        if (StringUtils.isNotBlank(value)) {
            String[] values = StringUtils.split(value, ",");
            if (values != null && values.length > 0) {
                for (String uri : values) {
                    excludeURIs.add(uri);
                }
            }
        }
    }

    public boolean isExcludeURIPrefix(String uri) {
        for (String value : excludeURIs) {
            if (value.equals("/")) {
                if (uri.equals(value)) {
                    return true;
                }
            } else if (uri.startsWith(value)) {
                return true;
            }
        }
        return false;
    }
}
