package cd.casic.plugin.core.register;

import cd.casic.plugin.dataobject.pojo.PluginInfo;
import cd.casic.plugin.function.IPluginProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @description: TODO
 * @author: mianbin
 * @date: 2025/5/22 20:08
 * @version: 1.0
 */
@Slf4j
@Component
public class ApplicationContextPluginProcessor implements IPluginProcessor {
    @Override
    public void initialize() throws Exception {

    }

    @Override
    public void registry(PluginInfo plugin) throws Exception {
        if (plugin.getApplicationContextIsRefresh()) {
            return;
        }
        plugin.getPluginApplicationContext().setClassLoader(plugin.getPluginWrapper().getPluginClassLoader());
        plugin.getPluginApplicationContext().getDefaultListableBeanFactory()
                .registerSingleton(plugin.getPluginWrapper().getPluginId().trim(),
                        plugin.getPluginWrapper().getPlugin());
        plugin.getPluginApplicationContext().refresh();
        plugin.setApplicationContextIsRefresh(true);
    }

    @Override
    public void unRegistry(PluginInfo plugin) throws Exception {
        // 获取插件ApplicationContext的DefaultListableBeanFactory实例
        DefaultListableBeanFactory beanFactory = plugin.getPluginApplicationContext().getDefaultListableBeanFactory();
        // 根据插件ID获取Bean的名称
        String[] beanNames = beanFactory.getBeanNamesForType(plugin.getPluginWrapper().getPlugin().getClass());
        Arrays.stream(beanNames)
                .filter(beanName -> beanName.equals(plugin.getPluginWrapper().getPluginId().trim()))
                .forEach(beanFactory::destroySingleton);
    }
}
