package org.qinan.safetyeval.start.config;

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import java.lang.reflect.Field;
import java.util.List;

@Configuration
public class SpringfoxWebMvcCompatConfig {

    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) {
                if (bean instanceof WebMvcRequestHandlerProvider) {
                    removePathPatternHandlerMappings(bean);
                }
                return bean;
            }
        };
    }

    @SuppressWarnings("unchecked")
    private static void removePathPatternHandlerMappings(Object bean) {
        Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
        if (field == null) {
            return;
        }
        field.setAccessible(true);
        List<RequestMappingInfoHandlerMapping> mappings =
                (List<RequestMappingInfoHandlerMapping>) ReflectionUtils.getField(field, bean);
        if (mappings != null) {
            mappings.removeIf(mapping -> mapping.getPatternParser() != null);
        }
    }
}
