package cd.casic.plugin.pf4j;

import lombok.extern.slf4j.Slf4j;
import org.pf4j.JarPluginRepository;

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class OpsJarPluginRepository extends JarPluginRepository {

    public OpsJarPluginRepository(Path... pluginsRoots) {
        this(Arrays.asList(pluginsRoots));
    }

    public OpsJarPluginRepository(List<Path> pluginsRoots) {
        super(pluginsRoots);
    }

    @Override
    public List<Path> getPluginPaths() {
        List<Path> pluginPaths = new ArrayList<>();
        for (Path pluginRoot : pluginsRoots){
            File rootDir = pluginRoot.toFile();

            scanForJars(rootDir.toPath(), pluginPaths);

        }
        return pluginPaths;
    }

    private void scanForJars(Path directory, List<Path> pluginPaths) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
            for (Path entry : stream) {
                if (Files.isDirectory(entry)) {
                    // 如果是目录，递归进入下一层
                    scanForJars(entry, pluginPaths);
                } else if (entry.getFileName().toString().endsWith(".jar")) {
                    // 如果是.jar文件，添加到结果列表
                    pluginPaths.add(entry);
                }
            }
        } catch (IOException e) {
            System.err.println("Error scanning directory " + directory + ": " + e.getMessage());
        }
    }


}
