package cd.casic.plugin.dataobject.dao;

import cd.casic.plugin.dataobject.pojo.PluginFacade;
import cd.casic.plugin.dataobject.pojo.PluginInfo;
import cd.casic.plugin.dataobject.dto.PluginSpecStorage;
import lombok.Data;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: 插件信息门面类 , 暂时的办法
 * @author: mianbin
 * @date: 2025/5/20 16:00
 * @version: 1.0
 */
@Data
public class PluginFacadeMemoryCache {
    private static final Map<String, PluginFacade> pluginFacadeMap = new ConcurrentHashMap<>(8);

    public static void putPluginSpec(String pluginId, PluginSpecStorage pluginDescriptorStorage) {
        pluginFacadeMap.computeIfAbsent(pluginId, k -> new PluginFacade())
                .setPluginSpecStorage(pluginDescriptorStorage);
    }

    public static PluginSpecStorage getPluginSepc(String pluginId) {
        return Optional.ofNullable(pluginFacadeMap.get(pluginId))
                .map(PluginFacade::getPluginSpecStorage)
                .orElse(null);
    }

    public static void putPluginInfo(String pluginId, PluginInfo pluginInfo) {
        pluginFacadeMap.computeIfAbsent(pluginId, k -> new PluginFacade())
                .setPluginInfo(pluginInfo);
    }

    public static PluginInfo getPluginInfo(String pluginId) {
        return Optional.ofNullable(pluginFacadeMap.get(pluginId))
                .map(PluginFacade::getPluginInfo)
                .orElse(null);
    }

    public static void putPluginClassloader(String pluginId, ClassLoader classLoader) {
        pluginFacadeMap.computeIfAbsent(pluginId, k -> new PluginFacade())
                .setClassLoader(classLoader);
    }

    public static ClassLoader getPluginClassLoader(String pluginId) {
        return Optional.ofNullable(pluginFacadeMap.get(pluginId))
                .map(PluginFacade::getClassLoader)
                .orElse(null);
    }

    public static void putPluginApplicationContext(String pluginId, AnnotationConfigApplicationContext applicationContext) {
        pluginFacadeMap.computeIfAbsent(pluginId, k -> new PluginFacade())
                .setApplicationContext(applicationContext);
    }

    public static AnnotationConfigApplicationContext getPluginApplicationContext(String pluginId) {
        return Optional.ofNullable(pluginFacadeMap.get(pluginId))
                .map(PluginFacade::getApplicationContext)
                .orElse(null);
    }

    public static void removePlugin(String pluginId) {
        pluginFacadeMap.remove(pluginId);
    }

    public static Map<String, PluginFacade> getAllPlugin() {
        return Collections.unmodifiableMap(pluginFacadeMap);
    }

}
