package cd.casic.plugin.core;

import cd.casic.plugin.config.PluginProperties;
import org.pf4j.DevelopmentPluginLoader;
import org.pf4j.PluginDescriptor;
import org.pf4j.PluginManager;

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

/**
 * @description: TODO
 * @author: mianbin
 * @date: 2025/5/13 10:50
 * @version: 1.0
 */
public class DevPluginLoader extends DevelopmentPluginLoader {

    private final PluginProperties pluginProperties;

    public DevPluginLoader(
            PluginManager pluginManager,
            PluginProperties pluginProperties
    ) {
        super(pluginManager);
        this.pluginProperties = pluginProperties;
    }

    @Override
    public ClassLoader loadPlugin(Path pluginPath, PluginDescriptor pluginDescriptor) {
        var classesDirectories = pluginProperties.getClassesDirectories();
        if (classesDirectories != null) {
            classesDirectories.forEach(
                    classesDirectory -> pluginClasspath.addClassesDirectories(classesDirectory)
            );
        }
        var libDirectories = pluginProperties.getLibDirectories();
        if (libDirectories != null) {
            libDirectories.forEach(
                    libDirectory -> pluginClasspath.addJarsDirectories(libDirectory)
            );
        }
        return super.loadPlugin(pluginPath, pluginDescriptor);
    }

    @Override
    public boolean isApplicable(Path pluginPath) {
        // 目录加载插件只能在dev模式下
        return Files.isDirectory(pluginPath);
    }
}

