package com.zivilon.cinder_loe.util;

import com.zivilon.cinder_loe.client.render.item.RenderHelper;
import com.zivilon.cinder_loe.CinderLoE;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import java.util.Vector;

import lotr.common.LOTRCreativeTabs;
import lotr.common.world.biome.LOTRBiome;
import lotr.common.item.LOTRItemArmor;
import lotr.common.item.LOTRMaterial;
import lotr.common.enchant.LOTREnchantment;
import lotr.common.enchant.LOTREnchantmentHelper;
import net.minecraft.item.ItemStack;

import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;

public class Utilities {

    public static int[] LOTRIntCache = null;
    public static LOTRBiome reflected_river;
    public static LOTRCreativeTabs reflected_tab_block;

    public static void initialize_reflects() {
        try {
            Field riverField = LOTRBiome.class.getField("river");
            reflected_river = (LOTRBiome)riverField.get(null);

        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void pre_init_reflects() {
        try {
            Field tabBlockField = LOTRCreativeTabs.class.getField("tabBlock");
            reflected_tab_block = (LOTRCreativeTabs)tabBlockField.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static EntityPlayerMP getPlayerByUUID(UUID playerUUID) {
        MinecraftServer server = MinecraftServer.getServer(); // Get the server instance
        if (server == null) {
            return null; // Server instance is not available
        }

        // Iterate through the list of online players and match UUID
        for (Object obj : server.getConfigurationManager().playerEntityList) {
            if (obj instanceof EntityPlayerMP) {
                EntityPlayerMP player = (EntityPlayerMP) obj;
                if (player.getUniqueID().equals(playerUUID)) {
                    return player;
                }
            } else {
                System.err.println("[CinderCore] Player list having non-players, WHAT?!?!?!");
            }
        }
        return null; // Player not found or not online
    }

    public static String toSnakeCase(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }

        StringBuilder builder = new StringBuilder();
        char[] chars = input.toCharArray();

        builder.append(Character.toLowerCase(chars[0]));
        for (int i = 1; i < chars.length; i++) {
            char c = chars[i];
            if (Character.isUpperCase(c)) {
                builder.append('_').append(Character.toLowerCase(c));
            } else {
                builder.append(c);
            }
        }

        return builder.toString();
    }

    public static void dumpClass(String className, String outputFilePath, Class<?> contextClass) {
        // Convert class name to a resource path
        String resourcePath = className.replace('.', '/') + ".class";
        // Use the class loader of the context class to find the resource
        try (InputStream classStream = contextClass.getClassLoader().getResourceAsStream(resourcePath)) {
            if (classStream == null) {
                System.err.println("Class " + className + " could not be found.");
                return;
            }
            try (OutputStream outputStream = new FileOutputStream(outputFilePath)) {
                // Copy the class stream to the output file
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = classStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                System.out.println("Dumped " + className + " to " + outputFilePath);
            } catch (IOException e) {
                System.err.println("Failed to write class file: " + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Failed to read class file: " + e.getMessage());
        }
    }

    public static void writeLog(String message) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("custom_log.txt", true))) {
            LocalDateTime now = LocalDateTime.now();
            String timestamp = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            writer.write(timestamp + " - " + message + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static EntityPlayer getPlayerByName(String player_name) {
        MinecraftServer server = MinecraftServer.getServer();
        if (server == null) {
            return null;
        }

        for (Object obj : server.getConfigurationManager().playerEntityList) {
    	    if (obj instanceof EntityPlayerMP) {
                EntityPlayer player = (EntityPlayer)obj;
			    String found_name = player.getCommandSenderName();
	            if (found_name.equals(player_name)) {
	                return player;
	            }
            }
        }
        return null; // Player not found or not online
    }

    public static boolean hasFireWeapon(String player_name) {
        EntityPlayer player = getPlayerByName(player_name);

        if (player == null) {
            System.out.println("[CinderLoE] Warning! Player not found: " + player_name);
            return false;
        }

        ItemStack held_item = player.getHeldItem();
        boolean has_fire = LOTREnchantmentHelper.hasEnchant(held_item, LOTREnchantment.fire);
        return has_fire;
    }

    public static int[] countNexArmour(String player_name) {
        EntityPlayer player = getPlayerByName(player_name);
        int[] nexPieces = new int[4];

        if (player == null) {
            System.out.println("[CinderLoE] Warning! Player not found: " + player_name);
            return nexPieces;
        }

        for (ItemStack armor : player.inventory.armorInventory) {
            if (armor != null && armor.getItem() instanceof LOTRItemArmor) {
                LOTRItemArmor itemArmor = (LOTRItemArmor) armor.getItem();
                if (itemArmor.getLOTRArmorMaterial() == CinderLoE.MATERIAL_NEX_ICE) {
                    nexPieces[0]++;
                } else if (itemArmor.getLOTRArmorMaterial() == CinderLoE.MATERIAL_NEX_FIRE) {
                    nexPieces[1]++;
                } else if (itemArmor.getLOTRArmorMaterial() == CinderLoE.MATERIAL_NEX_SHADOW) {
                    nexPieces[2]++;
                } else if (itemArmor.getLOTRArmorMaterial() == CinderLoE.MATERIAL_NEX_TOXIN) {
                    nexPieces[3]++;
                }
            }
        }

        if (nexPieces[0] == 4) nexPieces[0] = 5;
        if (nexPieces[1] == 4) nexPieces[1] = 5;
        if (nexPieces[2] == 4) nexPieces[2] = 5;
        if (nexPieces[3] == 4) nexPieces[3] = 5;

        return nexPieces;
    }

    public static boolean isArrayEmpty(int[] array) {
        for (int value : array) {
            if (value != 0) return false;
        }
        return true;
    }

}
