package eu.mhsl.minecraft.pixelpics;

import eu.mhsl.minecraft.pixelpics.commands.PixelPicsCommand;
import eu.mhsl.minecraft.pixelpics.render.render.DefaultScreenRenderer;
import eu.mhsl.minecraft.pixelpics.render.render.Renderer;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Objects;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public final class Main extends JavaPlugin {
    private static Main instance;
    private Renderer screenRenderer;

    public final NamespacedKey pictureIdFlag = Objects.requireNonNull(
        NamespacedKey.fromString("imageId".toLowerCase(), this),
        "Failed to create item-Flag Namespace"
    );

    @Override
    public void onEnable() {
        instance = this;
        extractJsonResources();

        Objects.requireNonNull(Bukkit.getPluginCommand("pixelPic"))
            .setExecutor(new PixelPicsCommand());

        Bukkit.getPluginCommand("test").setExecutor((sender, command, label, args) -> {
//            Dialog dialog = Dialog.create(
//                builder -> builder.empty()
//                    .base(
//                        DialogBase.builder(Component.text("Hello World")).build()
//                    )
//                    .type(DialogType.multiAction(
//                        List.of(
//                            ActionButton.builder(Component.text("Option 1")).action(DialogAction.staticAction(ClickEvent.callback(audience -> System.out.println("HIIIII")))).build(),
//                            ActionButton.builder(Component.text("Option 2")).action(DialogAction.customClick(Key.key("test"), null)).build(),
//                            ActionButton.builder(Component.text("Option 3")).action(DialogAction.commandTemplate("say hi")).build()
//                        ),
//                        ActionButton.builder(Component.text("Beenden")).build(),
//                        3
//                    ))
//
//            );
//            sender.showDialog(dialog);

            Material.getMaterial("acacia_button");
            Bukkit.broadcast(Component.text(Material.STONE.getBlockTranslationKey().replace("block.minecraft.", "")));

            if(!(sender instanceof Player))
                throw new IllegalStateException("Dieser Command kann nur von einem Spieler ausgeführt werden!");

            File blockDir = new File(getDataFolder(), "models/block");
            for (File file : blockDir.listFiles()) {
                String blockName = file.getName().substring(0, file.getName().lastIndexOf('.'));
                Material material = Material.getMaterial(blockName.toUpperCase());
                System.out.println(material);
                if(material == null) {
                    System.out.println(blockName);
                }
            }

            return true;
        });
    }

    public void extractJsonResources() {
        String resourcePath = "models/block/";
        File outputDir = new File(getDataFolder(), resourcePath);
        if (outputDir.exists()) return;
        outputDir.mkdirs();

        try {
            URL jarUrl = getClass().getProtectionDomain().getCodeSource().getLocation();
            File jarFile = new File(jarUrl.toURI());

            try (JarFile jar = new JarFile(jarFile)) {
                Enumeration<JarEntry> entries = jar.entries();

                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String entryName = entry.getName();

                    // Nur JSON-Dateien im gewünschten Ordner
                    if (entryName.startsWith(resourcePath) && entryName.endsWith(".json")) {
                        InputStream in = getResource(entryName);
                        if (in == null) continue;

                        File outFile = new File(getDataFolder(), entryName);
                        outFile.getParentFile().mkdirs(); // Ordnerstruktur sicherstellen

                        try (OutputStream out = new FileOutputStream(outFile)) {
                            byte[] buffer = new byte[1024];
                            int len;
                            while ((len = in.read(buffer)) != -1) {
                                out.write(buffer, 0, len);
                            }
                            System.out.println("Extrahiert: " + entryName);
                        }

                        in.close();
                    }
                }
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public Renderer getScreenRenderer() {
        if(this.screenRenderer == null) this.screenRenderer = new DefaultScreenRenderer();
        return this.screenRenderer;
    }

    public static Main getInstance() {
        return instance;
    }
}
