package com.ruoyi.framework.config.properties;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.lang3.RegExUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.ruoyi.common.annotation.Anonymous;

/**
 * 设置Anonymous注解允许匿名访问的url
 * 
 * @author ruoyi
 */
@Configuration
public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware
{
    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

    private ApplicationContext applicationContext;

    private List<String> urls = new ArrayList<>();

    public String ASTERISK = "*";

    @Override
    public void afterPropertiesSet()
    {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        map.keySet().forEach(info -> {
            HandlerMethod handlerMethod = map.get(info);
            Anonymous method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Anonymous.class);
            Anonymous controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Anonymous.class);
            if (method == null && controller == null)
            {
                return;
            }
            for (String url : resolveUrlPatterns(info))
            {
                urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK));
            }
        });
    }

    /**
     * 兼容 Ant 路径（PatternsCondition）与 PathPattern（PathPatternsCondition，Spring Boot 2.6+ 常见）。
     */
    private Set<String> resolveUrlPatterns(RequestMappingInfo info)
    {
        Set<String> patterns = new LinkedHashSet<>();
        if (info.getPatternsCondition() != null)
        {
            Set<String> antPatterns = info.getPatternsCondition().getPatterns();
            if (antPatterns != null)
            {
                patterns.addAll(antPatterns);
            }
        }
        if (info.getPathPatternsCondition() != null)
        {
            info.getPathPatternsCondition().getPatterns()
                    .forEach(pathPattern -> patterns.add(pathPattern.getPatternString()));
        }
        return patterns;
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException
    {
        this.applicationContext = context;
    }

    public List<String> getUrls()
    {
        return urls;
    }

    public void setUrls(List<String> urls)
    {
        this.urls = urls;
    }
}
