package cd.casic.plugin.core.register.database;

import cd.casic.plugin.OpsPluginDescriptor;
import cd.casic.plugin.core.register.filter.impl.DataBaseEntityFilter;
import cd.casic.plugin.dataobject.pojo.PluginInfo;
import cd.casic.plugin.function.IPluginProcessor;
import cd.casic.plugin.utils.dBUtils.SQLGenerator;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.pf4j.PluginDescriptor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description: TODO
 * @author: mianbin
 * @date: 2025/5/22 17:07
 * @version: 1.0
 */
@Slf4j
@Component
public class DatabaseProcessor implements IPluginProcessor {

    @Override
    public void initialize() throws Exception {
        log.info("Start to hand the Database Class for plugin");
    }

    @Override
    public void registry(PluginInfo plugin) throws Exception {
        DataBaseProperty dataBaseProperty;
        SQLGenerator sqlGenerator;
        PluginDescriptor descriptor = plugin.getPluginWrapper().getDescriptor();
        if (!(descriptor instanceof OpsPluginDescriptor)) {
            return;
        }
        OpsPluginDescriptor opsPluginDescriptor = (OpsPluginDescriptor) descriptor;
        if (StrUtil.isNotEmpty(opsPluginDescriptor.getConfigFileName())) {
            // 使用插件独立数据源
            AnnotationConfigApplicationContext pluginApplicationContext = plugin.getPluginApplicationContext();
            try {
                dataBaseProperty = pluginApplicationContext.getBean(DataBaseProperty.class);
            } catch (Exception e) {
                dataBaseProperty = null;
                log.info("插件未配置独立数据源");
            }
        } else {
            dataBaseProperty = null;
        }
        try {
            sqlGenerator = plugin.getMainApplicationContext().getBean(SQLGenerator.class);
        } catch (Exception e) {
            log.error("无法获取SqlGenerator类型的Bean对象");
            return;
        }
        List<Class<?>> entities = plugin.getGroupClass(DataBaseEntityFilter.GROUP_NAME);
        for (Class<?> entity : entities) {
            sqlGenerator.sqlDeleteGenerator(entity, dataBaseProperty, plugin.getPluginId());
            sqlGenerator.sqlGenerator(entity, dataBaseProperty, plugin.getPluginId());
        }
    }

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

    }
}
