package eu.mhsl.craftattack.teamLobby.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.*;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ResourceExtractor {
    public static final Path commonRessourcePath = Path.of("resources");

    public static void extractResourceFolder(String resourcePath, Path outputDir) {
        try {
            handle(resourcePath, outputDir);
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void handle(String resourcePath, Path outputDir) throws URISyntaxException, IOException {
        URL resourceURL = ResourceExtractor.class.getResource(resourcePath);
        if (resourceURL == null) {
            throw new IllegalArgumentException("Resource path not found: " + resourcePath);
        }

        if (resourceURL.getProtocol().equals("jar")) {
            String jarPath = resourceURL.getPath().substring(5, resourceURL.getPath().indexOf("!"));
            try (JarFile jar = new JarFile(Paths.get(jarPath).toFile())) {
                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();

                    if (name.startsWith(resourcePath.substring(1) + "/") && !entry.isDirectory()) {
                        InputStream is = jar.getInputStream(entry);
                        Path outPath = outputDir.resolve(name.substring(resourcePath.length()));
                        Files.createDirectories(outPath.getParent());
                        Files.copy(is, outPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            }
        } else {
            Path resourceDir = Paths.get(resourceURL.toURI());

            try(var files = Files.walk(resourceDir)) {
                files.forEach(source -> {
                    try {
                        Path destination = outputDir.resolve(resourceDir.relativize(source).toString());
                        if (Files.isDirectory(source)) {
                            Files.createDirectories(destination);
                        } else {
                            Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        }
    }
}