package com.ycwl.basic.aspectj;

import com.ycwl.basic.annotation.RequestToFile;
import com.ycwl.basic.config.CachedBodyHttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.stream.Collectors;

@Aspect
@Component
@Slf4j
public class HttpSaver {

    @Pointcut("@annotation(com.ycwl.basic.annotation.RequestToFile)")
    public void requestToFilePointCut() {
    }

    @After("requestToFilePointCut()")
    public void requestToFile() throws IOException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        saveRequestToFile(request);
    }

    public static void saveRequestToFile(HttpServletRequest request) throws IOException {
        File file = new File("./request/"+System.currentTimeMillis()+".http");
        // 写入文件
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        try (java.io.FileWriter writer = new java.io.FileWriter(file, true)) {
            writer.append(request.getMethod()).append(" ").append(request.getRequestURL());
            String queryString = request.getQueryString();
            if (queryString != null) {
                writer.append("?").append(queryString);
            }
            writer.append("\r\n");
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                writer.append(headerName).append(": ").append(request.getHeader(headerName)).append("\r\n");
            }
            writer.append("\r\n");
            // 获取body
            CachedBodyHttpServletRequest cachedRequest = (CachedBodyHttpServletRequest) request;
            writer.append(new String(cachedRequest.getCachedBody()));
            writer.append("\r\n");
        }
    }
}
