package com.qmth.boot.api.interceptor.impl;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.api.interceptor.AbstractInterceptor;
import com.qmth.boot.api.utils.RequestUtil;
import com.qmth.boot.core.logger.constant.LoggerConstant;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

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

@Component
public class MetricsInterceptor extends AbstractInterceptor implements ApiConstant, LoggerConstant {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 设置开始处理时间
        request.setAttribute(ATTRIBUTE_START_TIME, System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        long timecost = getTimecost(request);
        // 记录日志
        MDC.put(MDC_CALLER, RequestUtil.getAttribute(request, ATTRIBUTE_CALLER, "-"));
        log.info("{} {} {} {}ms", request.getMethod().toUpperCase(), request.getServletPath(), response.getStatus(),
                timecost);
        MDC.clear();
    }

    private long getTimecost(HttpServletRequest request) {
        Long startTime = RequestUtil.getAttribute(request, ApiConstant.ATTRIBUTE_START_TIME);
        if (startTime != null) {
            return System.currentTimeMillis() - startTime;
        } else {
            return -1;
        }
    }
}
