package cd.casic.plugin;

import cd.casic.plugin.dataobject.dao.PluginFacadeMemoryCache;
import cd.casic.plugin.dataobject.dto.PluginSpecStorage;
import cd.casic.plugin.utils.PluginDescriptorUtils;
import org.pf4j.PluginDescriptor;
import org.pf4j.PluginDescriptorFinder;
import org.pf4j.util.FileUtils;

import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @description: 优化代码
 * @author: mianbin
 * @date: 2025/5/12 19:19
 * @version: 1.0
 */
public class YamlPluginDescriptorFinder implements PluginDescriptorFinder {

    private final YamlPluginFinder yamlPluginFinder;

    public YamlPluginDescriptorFinder() {
        yamlPluginFinder = new YamlPluginFinder();
    }

    @Override
    public boolean isApplicable(Path pluginPath) {
        return Files.exists(pluginPath)
                && (Files.isDirectory(pluginPath) || FileUtils.isJarFile(pluginPath));
    }

    @Override
    public PluginDescriptor find(Path pluginPath) {
        PluginSpecStorage pluginSpecStorage = yamlPluginFinder.find(pluginPath);
        try {
            return PluginDescriptorUtils.storageOpsPluginDescriptor(pluginSpecStorage);
        } finally {
            PluginFacadeMemoryCache.putPluginSpec(pluginSpecStorage.getPluginId(), pluginSpecStorage);
        }
    }
}
