package com.elab.spring.config;

import com.elab.log.asepct.LogResponseBodyAdvice;
import com.elab.spring.anno.EnableElabSpring;
import com.elab.spring.exception.CommonException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.HashMap;
import java.util.Map;

/**
 * 开启客户端的注册
 * <p>
 * 集合@EnableElabSpring使用
 *
 * @author liukaixiong
 * @Email liukx@elab-plus.com
 * @date 2021/9/1 - 15:22
 */
public class ELabSpringClientsRegistrar implements ImportBeanDefinitionRegistrar {

    private Map<String, Class<?>> clazzMap = new HashMap<>();

    public ELabSpringClientsRegistrar() {
        clazzMap.put("enableRocketMQConfig", RmqConfiguration.class);
        clazzMap.put("enableThreadConfig", ThreadConfiguration.class);
        clazzMap.put("enableCatIdConfig", LogResponseBodyAdvice.class);
        clazzMap.put("enableCommonExceptionConfig", CommonException.class);
        clazzMap.put("enableSwaggerConfig", SwaggerConfigBean.class);
        clazzMap.put("enableMVCConfig", SpringMvcConfig.class);
        clazzMap.put("enableAopConfig", AopConfig.class);
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        Map<String, Object> defaultAttrs = metadata.getAnnotationAttributes(EnableElabSpring.class.getName(), true);
        registerClients(defaultAttrs, registry);
    }

    public void registerClients(Map<String, Object> defaultAttrs, BeanDefinitionRegistry registry) {
        defaultAttrs.forEach((K, V) -> {
            boolean enable = (boolean)defaultAttrs.getOrDefault(K, false);
            if (enable) {
                Class<?> configurationClazz = clazzMap.get(K);
                BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(configurationClazz);
                registry.registerBeanDefinition(configurationClazz.getSimpleName(), builder.getBeanDefinition());
            }
        });
    }

}
