package com.apobates.forum.thrones.admin.controller.helper;

import com.apobates.forum.thrones.admin.controller.form.ActionForm;
import com.apobates.forum.utils.Commons;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.SmartView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 为ActionForm的子类增加token赋值
 * 
 * @author xiaofanku
 * @since 20200610
 */
public class FormTokenParameterInterceptor extends HandlerInterceptorAdapter{
    private final static Logger logger = LoggerFactory.getLogger(FormTokenParameterInterceptor.class);
    
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("[ADM][FTPI][AFT]request uri: "+request.getRequestURI());
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("[ADM][FTPI][PST]request uri: "+request.getRequestURI());
        if (null != modelAndView && !isRedirectView(modelAndView)) {
            logger.info("[ADM][FTPI][PST]view name: "+modelAndView.getViewName());
            if (modelAndView.getModel().containsKey("form") && "GET".equals(request.getMethod().toUpperCase())) { //只为model中有form并且是GET method of Http
                try{
                    ActionForm af = (ActionForm)modelAndView.getModel().get("form");
                    af.setToken(Commons.randomAlphaNumeric(8));
                    //logger.info(String.format("[ADM][FTPI][PST]To %s view the %s form in the generated token %s", modelAndView.getViewName(), af.getClass().getSimpleName(), af.getToken()));
                }catch(NullPointerException | ClassCastException e){
                    //logger.info("为ActionForm设置token失败, 异常:"+e.getMessage());
                    if(logger.isDebugEnabled()){
                        logger.debug("为ActionForm设置token失败", e);
                    }
                }
            }
        }
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("[ADM][FTPI][PRE]request uri: "+request.getRequestURI());
        return true;
    }
    
    private boolean isRedirectView(ModelAndView mv) {
        String viewName = mv.getViewName();
        if (null != viewName && viewName.startsWith("redirect:/")) {
            return true;
        }
        View view = mv.getView();
        return (null != view && view instanceof SmartView && ((SmartView) view).isRedirectView());
    }
}