package com.jeequan.jeepay.core.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//@Component
@Slf4j
public class URIFilter implements Filter {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String uri = httpRequest.getRequestURI();

        // 判断请求的URI是否为静态资源，若是则不打印
        if (isStaticResource(uri)) {
            // 继续处理请求
            chain.doFilter(request, response);
        } else {
            log.info("Request URI: " + uri);
            log.info("Request method: " + httpRequest.getMethod());
            log.info("Request remote host: " + httpRequest.getRemoteHost());
            // 继续处理请求
            chain.doFilter(request, response);
        }
    }

    private boolean isStaticResource(String uri) {
        // 静态资源所在的默认路径
        String[] staticResourceLocations = {"/static/**", "/public/**", "/resources/**", "/META-INF/resources/**"};

        for (String location : staticResourceLocations) {
            if (pathMatcher.match(location, uri)) {
                return true;
            }
        }
        return false;
    }

    // 可以在这里实现其他Filter方法，但对于打印URI来说，doFilter()方法已足够
}
