package com.xydl.cac.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

@Component
@Slf4j
public class UrlFilter extends OncePerRequestFilter {

    PathMatcher pathMatcher = new AntPathMatcher();
    private List<String> urlWhiteList = Arrays.asList("/swagger-ui/**", "/swagger-resources/**", "/v3/api-docs/**",
            "/static/**", "/newcac/**");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String path = request.getRequestURI();
        for (String white : urlWhiteList) {
            if (pathMatcher.match(white, path)) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        String method = request.getMethod();
        StringBuilder str = new StringBuilder(method + " " + path + " called");
        Enumeration<String> params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String paramName = params.nextElement();
            str.append(", ").append(paramName).append("=").append(request.getParameter(paramName));
        }
        log.info(str.toString());

        if (path.startsWith("/cac-api/")) {
            path = path.replace("/cac-api/", "/");
            request.getRequestDispatcher(path).forward(request, response);
            return;
        }

        filterChain.doFilter(request, response);
    }
}
