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

import java.io.IOException;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.com.qmth.stmms.common.domain.WebUser;
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;

/**
 * 基础拦截器，用于解析session构造基础WebUser对象
 * 
 * @author LS
 * 
 */
public class CommonInterceptor extends HandlerInterceptorAdapter {

    private static Logger log = LoggerFactory.getLogger(CommonInterceptor.class);

    @Autowired
    private SessionService sessionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        buildWebUser(request, response);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        String uri = request.getRequestURI();
        if (!uri.startsWith("/api")) {
            try {
                sessionService.put(request, response, RequestUtils.getSession(request));
            } catch (Exception e) {
                log.error("stmms session save faile!", e);
            }
        }

    }

    /**
     * 强制失效session，执行请求跳转
     * 
     * @param request
     * @param response
     * @param redirectURI
     * @return
     * @throws IOException
     */
    protected boolean sessionExpire(HttpServletRequest request, HttpServletResponse response, String redirectURI)
            throws IOException {
        StmmsSession session = RequestUtils.getSession(request);
        session.setInvalid(true);
        sessionService.put(request, response, session);
        response.sendRedirect(request.getContextPath() + redirectURI);
        return false;
    }

    /**
     * 强制执行请求跳转
     * 
     * @param request
     * @param response
     * @param redirectURI
     * @return
     * @throws IOException
     */
    protected boolean redirect(HttpServletRequest request, HttpServletResponse response, String redirectURI)
            throws IOException {
        response.sendRedirect(request.getContextPath() + redirectURI);
        return false;
    }

    /**
     * 从session中构造WebUser对象
     * 
     * @param request
     * @param response
     * @throws Exception
     */
    private void buildWebUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        WebUser wu = WebUser.buildFromSession(RequestUtils.getSession(request));
        if (wu != null) {
            RequestUtils.setWebUser(request, wu);
        }
    }
}
