package cn.xianyum.framwork.config;

import cn.xianyum.common.annotation.Permission;
import com.alibaba.fastjson2.JSONObject;
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 java.util.*;
import java.util.regex.Pattern;

/**
 * 设置Permission注解允许匿名访问的url
 *
 */
@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",RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        map.keySet().forEach(info -> {
            HandlerMethod handlerMethod = map.get(info);
            if(null == info.getPatternsCondition()){
                return;
            }
            // 获取方法上边的注解 替代path variable 为 *
            Permission method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Permission.class);

            try {
                Optional.ofNullable(method).filter(p -> p.publicApi()).ifPresent(anonymous -> Objects.requireNonNull(info.getPatternsCondition().getPatterns())
                        .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))));
            }catch (Exception e){
                System.out.println(e);
            }


            // 获取类上边的注解, 替代path variable 为 *
            Permission controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Permission.class);
            Optional.ofNullable(controller).filter(p -> p.publicApi()).ifPresent(anonymous -> Objects.requireNonNull(info.getPatternsCondition().getPatterns())
                    .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))));
        });
    }

    @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;
    }
}
