package cn.stylefeng.guns.config.web;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class EmptyResourceFilter implements Filter {

    private static final Map<String, Boolean> NEED_TO_CACHE_FLAG = new HashMap<>();

    public static final String GUNS_DEVOPS_ASSETS_PREFIX = "/guns-devops/assets";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String requestURI = httpServletRequest.getRequestURI();

        if (requestURI.startsWith(GUNS_DEVOPS_ASSETS_PREFIX)) {

            Boolean urlHasEmpty = NEED_TO_CACHE_FLAG.get(requestURI);
            if (urlHasEmpty != null) {
                if (urlHasEmpty) {
                    this.doEmptyResourceReturn(response);
                } else {
                    chain.doFilter(request, response);
                }
                return;
            }

            String resourcePath = StrUtil.removePrefix(requestURI, "/");
            URL resource = ResourceUtil.getResource(resourcePath);

            if (resource == null) {
                chain.doFilter(request, response);

                NEED_TO_CACHE_FLAG.put(requestURI, false);

                return;
            }

            String content = ResourceUtil.readUtf8Str(resourcePath);
            if (ObjectUtil.isEmpty(content)) {
                doEmptyResourceReturn(response);

                NEED_TO_CACHE_FLAG.put(requestURI, true);
            }

            else {
                chain.doFilter(request, response);

                NEED_TO_CACHE_FLAG.put(requestURI, false);
            }

            return;
        }

        chain.doFilter(request, response);
    }

    private void doEmptyResourceReturn(ServletResponse response) throws IOException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.getWriter().write("");
    }

    @Override
    public void destroy() {

    }
}
