package com.fos.core.filter;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fos.core.conf.GConstants;
import com.fos.core.util.AgentUtil;
import com.fos.core.util.Util;

/**
 * 手机端视图拦截器
 * @team BBDTEK Dev Team
 * @version 1.0
 * @time 2016-03-22
 * 
 */
public class MobileInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
            Object handler) throws Exception {
//        request.setAttribute("clientip", Util.getOnlineIP(request));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
            ModelAndView modelAndView) throws Exception {
        if(request == null || modelAndView == null)
            return ;
        String basePath = Util.getBasePath(request);
        modelAndView.addObject("BASE_PATH", basePath);// 设置请求基本URL
        modelAndView.addObject("CONTEXT_PATH", Util.getContextPath(request));// 设置请求基本URL
//        response.setHeader("Access-Control-Allow-Origin",  "*");
        if (GConstants.IS_MOBILE_INTERCEPTOR && 
                modelAndView != null && AgentUtil.isMobileOrTablet(request)){
            // 如果是手机或平板访问的话，则跳转到手机视图页面。
            if(!StringUtils.startsWithIgnoreCase(modelAndView.getViewName(), "redirect:")){
                modelAndView.setViewName("mobile/" + modelAndView.getViewName());
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
            Object handler, Exception ex) throws Exception {
//        response.setHeader("Access-Control-Allow-Origin",  "*");
    }
}
