package com.sonic.common.log;

import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

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

import com.sonic.common.AppRuntime;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;

/**
 * @author code
 */
@Slf4j
public class TraceInterceptor implements HandlerInterceptor {

    private AppRuntime appRuntime;

    public static final String TRACE_VERBOSE_PARAM = "__print_verbose";

    public TraceInterceptor(AppRuntime appRuntime) {
        this.appRuntime = appRuntime;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (CollectionUtils.contains(request.getParameterNames(), TRACE_VERBOSE_PARAM)) {
            Map<String, String> headers = Maps.newHashMap();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (Objects.nonNull(headerNames) && headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                headers.put(name, request.getHeader(name));
            }
            log.info("request url = {}, params = {}, headers = {}, appRuntime = {}",
                    request.getRequestURI(), request.getParameterMap(), headers, appRuntime);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (CollectionUtils.contains(request.getParameterNames(), TRACE_VERBOSE_PARAM)) {
            Map<String, Collection<String>> headers = response.getHeaderNames().stream().collect(Collectors.toMap(h -> h,
                    h -> Optional.ofNullable(response.getHeaders(h)).orElse(Collections.emptyList())));
            log.info("response headers = {}, status = {}, appRuntime = {}", headers, response.getStatus(), appRuntime);
        }
    }
}
