package cd.casic.plugin.register;

import cd.casic.plugin.PluginInfo;
import cd.casic.plugin.register.group.filter.impl.BasicBeanFilter;
import cd.casic.plugin.register.group.filter.impl.ControllerFilter;
import cd.casic.plugin.register.group.filter.impl.MapperFilter;
import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;

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

public class SpringBeanRegisterHandler implements BasePluginHandler {
    @Override
    public void initialize() throws Exception {

    }

    @Override
    public void registry(PluginInfo plugin) throws Exception {
        List<Class<?>> basicBeanClassList = new ArrayList<>();
        basicBeanClassList.addAll(plugin.getGroupClass(BasicBeanFilter.GROUP_NAME));
        basicBeanClassList.addAll(plugin.getGroupClass(MapperFilter.GROUP_NAME));
        basicBeanClassList.addAll(plugin.getGroupClass(ControllerFilter.GROUP_NAME));
//        if(!basicBeanClassList.isEmpty()){
//            plugin.getPluginApplicationContext().register(basicBeanClassList.toArray(new Class[0]));
//        }
        basicBeanClassList.forEach(clazz -> {
            AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(clazz);
            beanDefinition.setBeanClass(clazz);
            BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
            String beanName = beanNameGenerator.generateBeanName(beanDefinition, plugin.getPluginApplicationContext());
            plugin.getPluginApplicationContext().registerBeanDefinition(beanName, beanDefinition);
        });
    }

    @Override
    public void unRegistry(PluginInfo plugin) throws Exception {

    }
}
