package hu.jgj52.pvpcore.Utils;

import hu.jgj52.pvpcore.Main;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.postgresql.util.PGobject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class Kits {
    private final Main plugin;

    public Kits(Main plugin) {
        this.plugin = plugin;
    }

    public static String itemStackArrayToBase64(ItemStack[] items) {
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            try (BukkitObjectOutputStream out = new BukkitObjectOutputStream(byteOut)) {
                out.writeInt(items.length);
                for (ItemStack item : items) {
                    out.writeObject(item);
                }
            }
            return Base64.getEncoder().encodeToString(byteOut.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static ItemStack[] itemStackArrayFromBase64(String data) {
        try {
            byte[] bytes = Base64.getDecoder().decode(data);
            try (BukkitObjectInputStream in = new BukkitObjectInputStream(new ByteArrayInputStream(bytes))) {
                int size = in.readInt();
                ItemStack[] items = new ItemStack[size];
                for (int i = 0; i < size; i++) {
                    items[i] = (ItemStack) in.readObject();
                }
                return items;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ItemStack[0];
        }
    }

    public ItemStack[] getKit(String gamemode, Player player, boolean defaultKit) throws ExecutionException, InterruptedException {
        Database.QueryResult result = plugin.db.from("pvpcore_kits")
                .eq("name", gamemode)
                .execute()
                .get();

        if (result.isEmpty()) return new ItemStack[0];

        Map<String, Object> kitRow = result.data.get(0);
        String kitId = kitRow.get("id").toString();
        String kitString = (String) kitRow.get("content");

        if (!defaultKit) {
            Database.QueryResult pl = plugin.db.from("pvpcore_players")
                    .eq("uuid", player.getUniqueId())
                    .execute()
                    .get();

            if (!pl.isEmpty()) {
                Map<String, Object> playerRow = pl.data.get(0);
                Object kitsObj = playerRow.get("kits");
                if (kitsObj != null) {
                    try {
                        String playerKitsStr = kitsObj instanceof PGobject pg ? pg.getValue() : kitsObj.toString();
                        if (!playerKitsStr.isEmpty()) {
                            com.google.gson.Gson gson = new com.google.gson.Gson();
                            java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<String, String>>() {}.getType();
                            Map<String, String> playerKits = gson.fromJson(playerKitsStr, type);
                            if (playerKits.containsKey(kitId)) {
                                kitString = playerKits.get(kitId);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        if (kitString == null || kitString.isEmpty()) return new ItemStack[0];

        return itemStackArrayFromBase64(kitString);
    }
}
