package com.codvision.webcore.config.encrypt.resolver;

import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 调整自定义参数解析器优先级
 * @author hxl
 */
@Component
@RequiredArgsConstructor
@ConditionalOnBean(ApiSecretRequestParamResolver.class)
public class ApiSecretResolverBeanPostProcessor implements BeanPostProcessor {

    private final ApiSecretRequestParamResolver requestParamResolver;
    private static final String HANDLER_ADAPTER = "requestMappingHandlerAdapter";

    @Override
    public Object postProcessAfterInitialization(@Nullable Object bean, @Nullable String beanName) throws BeansException {
        if (HANDLER_ADAPTER.equals(beanName)) {
            RequestMappingHandlerAdapter adapter = (RequestMappingHandlerAdapter) bean;
            if (adapter != null) {
                List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
                argumentResolvers.add(requestParamResolver);
                if (CollectionUtils.isNotEmpty(adapter.getArgumentResolvers())) {
                    argumentResolvers.addAll(adapter.getArgumentResolvers());
                }

                adapter.setArgumentResolvers(argumentResolvers);
            }
        }

        return bean;
    }
}
