package com.yihu.hos.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 校验用户是否已登录过滤器
 * add by hzp at 2016-03-03
 */
public class CheckLoginFilter implements Filter {

    private FilterConfig filterConfig = null;
    private String redirectURL = null;
    private List notCheckURLList = new ArrayList();

    public CheckLoginFilter() {
    }

    public void destroy() {
        notCheckURLList.clear();
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        Object userInfo = session.getAttribute("userInfo");
        if(!filterList(request) && userInfo==null){
            //重定向到指定页面
            response.sendRedirect(request.getContextPath() + redirectURL);
        }else{
            //继续响应请求
            chain.doFilter(servletRequest, servletResponse);
        }
    }

    public void init(FilterConfig fConfig) throws ServletException {
        this.filterConfig = fConfig;
        redirectURL = filterConfig.getInitParameter("redirectURL");
        String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");
        if(notCheckURLListStr!=null && notCheckURLListStr.length()>0){
            //将字符串转化为list
            String[] list = notCheckURLListStr.split(";");
            for(String str : list)
            {
                notCheckURLList.add(str);
            }

        }
    }
    /**
     * 校验当前请求是否在不过滤的列表中
     * @param request
     * @return
     */
    private boolean filterList(HttpServletRequest request)
    {
        String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
        if(notCheckURLList.contains(uri)) {
            return true;
        }
        else{
            // 不过滤的uri
            String[] notFilter = new String[] {"/develop"};
            for(String s : notFilter)
            {
                if (uri.indexOf(s) == 0)
                {
                    // 如果uri中包含不过滤的uri，则不进行过滤
                    return true;
                }
            }
        }

        return false;
    }

}