package com.storlead.framework.web.interceptor;

import com.storlead.framework.core.context.Context;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

public class AllRequestInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AllRequestInterceptor.class);
    public static final String URL_REQUEST_TIME_KEY = "URL_REQUEST_TIME_KEY";

    /**
     * 求之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String method = request.getMethod();
        System.out.println("method = " + method);
        if ("OPTIONS".equals(method)) {
            return false;
        }
        return true;
    }

    /**
     * 后处理 , 但未进行页面渲染
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    /**
     * 输出每个API请求处理时间的 log
     * 说明：(可以在AllRequestFilter chain.doFilter前后执行， 但这样文档swagger的 html,js,css 也会有log产生)
     **/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        try {
            long endTime = System.currentTimeMillis();
            // modified by Tiny 从上下文中获取请求开始时间
            // String requestTime = (String) request.getAttribute(URL_REQUEST_TIME_KEY);
            String requestTime = Context.getContext().getAttribute(URL_REQUEST_TIME_KEY, String.class);
            if (StringUtils.isNotBlank(requestTime)) {
//                long consumeTime = endTime - Long.parseLong(requestTime);
//                String ip = NetworkUtils.getIpAddress(request);
            }
        } catch (Exception e) {

        }
        super.afterCompletion(request, response, handler, ex);
    }
}
