package com.ced.sip.common.interceptor;

import java.util.Enumeration;
import java.net.URLDecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.ced.base.exception.BaseException;
import com.ced.sip.common.TableStatus;
import com.ced.sip.common.action.supplier.WebIndexAction;
import com.ced.sip.common.action.supplier.WebMobileIndexAction;
import com.ced.sip.common.entity.SessionInfo;
import com.ced.sip.common.utils.StringUtil;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 登录拦截器，判断用户是否登录
 * 
 * @author ted
 * 
 */
public class LoginInterceptor implements Interceptor {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = LogManager.getLogger(LoginInterceptor.class);

	public void init() {
	}

	public String intercept(ActionInvocation invocation) throws BaseException {

		String result = null;
		try {
			logger.debug("login Interceptor");
			// 通过核心调度器invocation来获得调度的Action上下文
			ActionContext actionContext = invocation.getInvocationContext();
			HttpServletRequest req = (HttpServletRequest)actionContext.get(ServletActionContext.HTTP_REQUEST);  
			HttpServletResponse res = (HttpServletResponse)actionContext.get(ServletActionContext.HTTP_RESPONSE);
			Object action = (Action) invocation.getAction();
			//System.out.println(action.getClass());
			//设置HttpOnly
			String sessionid = req.getSession().getId();
			res.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");
			if(action instanceof WebIndexAction||action instanceof WebMobileIndexAction){
				result = invocation.invoke();
			}else{
			//判断用户是否登录
			SessionInfo loginInfo = (SessionInfo) actionContext.getSession().get(TableStatus.LOGIN_INFO_KEY);
			String path = req.getRequestURI();//url
			String sessionId = ServletActionContext.getRequest().getParameter("jssessionId");
			if (path.contains("jssessionId")&&StringUtil.isBlank(sessionId)) {
				result = "timeout";
			}else if (loginInfo == null) {
				result = "timeout";
			} else{
				result = invocation.invoke();		
			}
			}

		} catch (Exception e) {
			logger.error("登录拦截器校验报错！", e);
			throw new BaseException("登录拦截器校验报错！", e);
		}
		return result;
	}

	public void destroy() {

	}
}
