package com.xt.hb.gis.system;

import java.io.IOException;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.xt.hb.gis.common.GlobalData;
import com.yuanxd.tools.io.http.HttpResultType;
import com.yuanxd.tools.io.http.HttpUtil;
import com.yuanxd.tools.io.http.RequestBean;
import com.yuanxd.tools.io.http.ResponseBean;
import com.yuanxd.tools.utils.string.StringUtils;

/**
 * 安全认证过滤器
 */
public class LoginFilter implements Filter {
	private final static Logger LOGGER = Logger.getLogger(LoginFilter.class);

	private String[] pass_url_filters = { "/yjpt/upload.*" };

	/**
	 * 初始化
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	/**
	 * 执行过滤
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		long startTime = System.currentTimeMillis();
		String request_uri = null;
		if ((request instanceof HttpServletRequest)) {
			HttpServletRequest httpReq = (HttpServletRequest) request;
			HttpServletResponse httpResp = (HttpServletResponse) response;
			request_uri = httpReq.getRequestURI();
			boolean pass = false;
			for (String pass_url : pass_url_filters) {
				if (request_uri.matches(pass_url)) {
					pass = true;
					break;
				}
			}
			if (!pass) {
				if (!this.checkSession(httpReq, httpResp)) {
					return;
				}
			}

		}
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
			LOGGER.error("error occured,url:" + request_uri);
			throw new RuntimeException(e);
		}
		long cost = System.currentTimeMillis() - startTime;
		// 耗时监控
		if (cost > 5000) {
			LOGGER.info("cost " + cost / 1000.0 + ":" + request_uri);
		}
	}

	/**
	 * 检查是否已登陆
	 * 
	 * @param httpReq
	 * @param httpResp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	private boolean checkSession(HttpServletRequest httpReq, HttpServletResponse httpResp)
			throws ServletException, IOException {
		// session过期
		if (httpReq.getSession(false) == null) {
			return checkToken(httpReq);
		}
		// 检查是否登录
		HttpSession session = httpReq.getSession();
		String st = (String) session.getAttribute(GlobalData.SESSION_TOKEN);
		if (null == st) {
			return checkToken(httpReq);
		}
		return true;
	}

	private boolean checkToken(HttpServletRequest httpReq) {
		HttpSession session = httpReq.getSession();
		String token = httpReq.getParameter("token");
		if (StringUtils.hasText(token)||true) {
			RequestBean req = new RequestBean(HttpResultType.STRING);
			req.setUrl(GlobalData.SESSION_VALID_URL + token);
			ResponseBean resp = HttpUtil.getInstance().execute(req);
			if ("true".equals(resp.getStringResult()) || GlobalData.isDevelop) {
				session.setAttribute(GlobalData.SESSION_TOKEN, token);
				return true;
			}
		}
		return true;
	}

	public void destroy() {
	}

}
