package com.mzh.library.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class CharacterEncodingFilter implements Filter {
    private String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) {
        String configuredEncoding = filterConfig.getInitParameter("encoding");
        if (configuredEncoding != null && !configuredEncoding.trim().isEmpty()) {
            encoding = configuredEncoding.trim();
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        if (isHtmlRequest(request)) {
            response.setContentType("text/html;charset=" + encoding);
        }
        chain.doFilter(request, response);
    }

    private boolean isHtmlRequest(ServletRequest request) {
        if (!(request instanceof HttpServletRequest)) {
            return true;
        }

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String contextPath = httpRequest.getContextPath();
        String requestUri = httpRequest.getRequestURI();
        String path = requestUri.substring(contextPath.length());
        return !path.startsWith("/static/")
            && !path.equals("/favicon.ico")
            && !hasStaticAssetExtension(path);
    }

    private boolean hasStaticAssetExtension(String path) {
        String normalizedPath = path.toLowerCase();
        return normalizedPath.endsWith(".css")
            || normalizedPath.endsWith(".js")
            || normalizedPath.endsWith(".png")
            || normalizedPath.endsWith(".jpg")
            || normalizedPath.endsWith(".jpeg")
            || normalizedPath.endsWith(".gif")
            || normalizedPath.endsWith(".svg")
            || normalizedPath.endsWith(".ico")
            || normalizedPath.endsWith(".woff")
            || normalizedPath.endsWith(".woff2")
            || normalizedPath.endsWith(".ttf")
            || normalizedPath.endsWith(".map");
    }
}
