package cd.casic.plugin.core.register;

import cd.casic.plugin.dataobject.pojo.PluginInfo;
import cd.casic.plugin.function.IPluginProcessor;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.pf4j.util.FileUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import static cd.casic.plugin.constants.PluginConstants.PLUGINS_RESOURCES_DIR;

/**
 * @description: TODO
 * @author: mianbin
 * @date: 2025/5/22 20:14
 * @version: 1.0
 */
@Slf4j
@Component
public class ResourcesProcessor implements IPluginProcessor {
    @Override
    public void initialize() throws Exception {

    }

    @Override
    public void registry(PluginInfo plugin) throws Exception {
        Path pluginPath = plugin.getPluginWrapper().getPluginPath();
        Set<String> staticClassPathLocations = plugin.getStaticClassPathLocations();
        File jarFile = null;
        if (Files.isDirectory(pluginPath)) {
            List<File> jars = FileUtils.getJars(pluginPath);
            jarFile = jars.get(0);
        } else if (pluginPath.toFile().getName().toLowerCase().endsWith(".jar")) {
            jarFile = pluginPath.toFile();
        } else {
            throw new RuntimeException("不正确的pluginPath");
        }
        Enumeration<JarEntry> jarEntries = new JarFile(jarFile).entries();
        File file = new File(PLUGINS_RESOURCES_DIR + File.separator + plugin.getPluginId());
        if (!file.exists()) {
            FileUtil.mkdir(file);
        }
        FileUtil.clean(file);
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = jarEntries.nextElement();
            String jarEntryName = entry.getName();
            for (String staticClassPathLocation : staticClassPathLocations) { //staticClassPathLocation里读取到所有静态资源的位置 然后将以插件为单位 打包到web的static目录下 即可访问
                if (!staticClassPathLocation.equals(jarEntryName) && jarEntryName.startsWith(staticClassPathLocation)
                        && !jarEntryName.endsWith(".class") && !entry.isDirectory()) {
                    URL url = new URL("jar:file:" + jarFile.getAbsolutePath() + "!/" + jarEntryName);
                    JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
                    InputStream in = jarConnection.getInputStream();
                    File file1 = new File(file.getAbsolutePath() + File.separator + jarEntryName);
                    FileUtil.touch(file1.getAbsolutePath());
                    int index;
                    byte[] bytes = new byte[1024];
                    FileOutputStream downloadFile = new FileOutputStream(file.getAbsolutePath() + File.separator + jarEntryName);
                    while ((index = in.read(bytes)) != -1) {
                        downloadFile.write(bytes, 0, index);
                        downloadFile.flush();
                    }
                    downloadFile.close();
                    in.close();
                    JarFile currJarFile = jarConnection.getJarFile();
                    currJarFile.close();
                }
            }
        }
    }

    @Override
    public void unRegistry(PluginInfo plugin) throws Exception {
        File file = new File(PLUGINS_RESOURCES_DIR + File.separator + plugin.getPluginId());
        if (file.exists()) {
            FileUtil.del(file.getAbsolutePath());
        }
    }
}
