package com.game.framework.interceptor;

import com.game.common.utils.SecurityUtils;
import com.game.common.utils.ip.IpUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;

@Log4j2
@Component
public class RequestLoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
            log.info("IP:{},UserId:{},Request Method: {},Version: {}, URL: {}",
                    IpUtils.getIpAddr(request),
                    userId,
                    request.getMethod(),
                    request.getHeader("Version"),
                    request.getRequestURL());
//                    request.getParameterMap());
        }catch (Exception e){

        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.info("Response Status: {}", response.getStatus());
    }

    public String getBodyParameter(HttpServletRequest request) {
        try {
            StringBuilder body = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                body.append(line);
            }
            return body.toString();
        }catch (Exception e){

        }
        return "";
    }

}
