import { ItemStack, world } from "@minecraft/server"


export class SpikeComponent {
    constructor() {
        this.onStepOn = this.onStepOn.bind(this);
        this.onPlace = this.onPlace.bind(this);

        this.Banned_entities = [
            "minecraft:ender_dragon",
            "minecraft:wither",
            //   "minecraft:elder_guardian",
            //    "minecraft:guardian",
            "minecraft:npc",
        ]

        this.XP_DROPS = {
            "passive": {
                "1-2": [
                    "minecraft:allay",
                    "minecraft:bat",
                    "minecraft:npc",
                    "minecraft:snow_golem",
                    "minecraft:tadpole",
                    "minecraft:villager",
                    "minecraft:villager_v2",
                    "minecraft:wandering_trader"
                ],
                "1-3": [
                    "minecraft:axolotl",
                    "minecraft:camel",
                    "minecraft:cat",
                    "minecraft:chicken",
                    "minecraft:cod",
                    "minecraft:cow",
                    "minecraft:donkey",
                    "minecraft:fox",
                    "minecraft:frog",
                    "minecraft:glow_squid",
                    "minecraft:horse",
                    "minecraft:mooshroom",
                    "minecraft:ocelot",
                    "minecraft:parrot",
                    "minecraft:pig",
                    "minecraft:pufferfish",
                    "minecraft:rabbit",
                    "minecraft:sheep",
                    "minecraft:skeleton_horse",
                    "minecraft:sniffer",
                    "minecraft:squid",
                    "minecraft:strider",
                    "minecraft:tropical_fish",
                    "minecraft:turtle",
                    "minecraft:zombie_horse"
                ],
                "2-3": ["minecraft:strider"]
            },
            "neutral": {
                "3-5": [
                    "minecraft:iron_golem"
                ],
                "1-3": [
                    "minecraft:bee",
                    "minecraft:dolphin",
                    "minecraft:goat",
                    "minecraft:llama",
                    "minecraft:panda",
                    "minecraft:polar_bear",
                    "minecraft:trader_llama",
                    "minecraft:wolf"
                ],
                "5-13": [
                    "minecraft:cave_spider",
                    "minecraft:enderman",
                    "minecraft:piglin",
                    "minecraft:spider"
                ]
            },
            "hostile": {
                "10-10": [
                    "minecraft:blaze",
                    "minecraft:evocation_illager",
                    "minecraft:guardian"
                ],
                "5-13": [
                    "minecraft:creeper",
                    "minecraft:drowned",
                    "minecraft:ghast",
                    "minecraft:hoglin",
                    "minecraft:husk",
                    "minecraft:phantom",
                    "minecraft:pillager",
                    "minecraft:shulker",
                    "minecraft:silverfish",
                    "minecraft:skeleton",
                    "minecraft:stray",
                    "minecraft:vex",
                    "minecraft:vindicator",
                    "minecraft:witch",
                    "minecraft:wither_skeleton",
                    "minecraft:zombie",
                    "minecraft:zombie_pigman",
                    "minecraft:zombie_villager",
                    "minecraft:zoglin"
                ],
                "12000-12000": ["minecraft:ender_dragon"],
                "100-150": ["minecraft:warden", "minecraft:elder_guardian"],
                "3-3": ["minecraft:endermite"],
                "4-4": [
                    "minecraft:large_slime",
                    "minecraft:large_magma_cube"
                ],
                "2-2": [
                    "minecraft:medium_slime",
                    "minecraft:medium_magma_cube"
                ],
                "1-1": [
                    "minecraft:small_slime",
                    "minecraft:small_magma_cube"
                ],
                "20-20": [
                    "minecraft:ravager",
                    "minecraft:piglin_brute"
                ],
                "50-50": ["minecraft:wither"]
            }
        };
    }
    onPlace(e) {
        const block = e.block;
        if (block.below().permutation.matches("pb_red:xp_tank")) {
            block.dimension.runCommand(`tellraw @p {"rawtext":[{"text":"§bThis Spike is now linked to the Xp Tank below"}]}`)
            block.dimension.runCommand(`playsound random.toast @a ${block.location.x} ${block.location.y} ${block.location.z}`)
        }
    }

    onStepOn(e) {
        const block = e.block;
        // console.warn("spike");
        for (const aboveEntity of block.dimension.getEntitiesAtBlockLocation(block.location)) {

            if (aboveEntity.getComponent('minecraft:health') && (!this.Banned_entities.includes(aboveEntity.typeId)) && (!this.loadIgnoredEntities("Spike").includes(aboveEntity.typeId.replace("minecraft:", "").replace("_v2", "")))) {
                if (aboveEntity.typeId == "minecraft:player" && ["spectator", "creative"].includes(aboveEntity.getGameMode())) {
                    return
                }
                let currentHealth = aboveEntity.getComponent('minecraft:health').currentValue;
                // console.warn(currentHealth)
                if (currentHealth <= 10) {

                    if (block.below().permutation.matches("pb_red:xp_tank")) {

                        if (block.permutation.matches("pb_red:lava_spike")) {
                            aboveEntity.setOnFire(3, false)
                        }
                        if (["minecraft:guardian", "minecraft:elder_guardian", "minecraft:witch"].includes(aboveEntity.typeId)) {
                            aboveEntity.runCommand("damage @s 30 entity_attack")
                        } else {
                            aboveEntity.runCommand("damage @s 30 entity_attack entity @s")
                        }
                        block.dimension.runCommand(`playsound item.trident.hit @a ${block.location.x} ${block.location.y} ${block.location.z} 0.5`)
                        let experienceValue = this.getExperienceValue(aboveEntity.typeId);

                        if (!aboveEntity.hasTag('AlreadyDead')) {
                            aboveEntity.addTag("AlreadyDead")
                            // console.warn("no xp damage")
                            if (experienceValue > 0) {
                                block.dimension.spawnEntity("pb_red:xp_tank_updater_dummy", {
                                    x: e.block.location.x + 0.5,
                                    y: e.block.location.y - 0.1,
                                    z: e.block.location.z + 0.5
                                }).addTag(`pb_red:xp_tank_updater_xp_level:${experienceValue}`)
                            }
                        }
                    } else {
                        // console.warn("xp damage")
                        block.dimension.runCommand(`playsound item.trident.hit @a ${block.location.x} ${block.location.y} ${block.location.z} 0.5`)
                        if (block.permutation.matches("pb_red:lava_spike")) {
                            aboveEntity.setOnFire(3, false)
                        }
                        aboveEntity.runCommand("damage @s 30 entity_attack entity @p")
                    }
                } else {
                    let verticalKb = 0.2
                    if (["minecraft:ravager", "minecraft:iron_golem", "minecraft:hoglin", "minecraft:zoglin", "minecraft:witch"].includes(aboveEntity.typeId)) verticalKb = 0.4

                    aboveEntity.teleport({ x: aboveEntity.location.x, y: aboveEntity.location.y + verticalKb, z: aboveEntity.location.z })
                    if (block.permutation.matches("pb_red:lava_spike")) {
                        aboveEntity.setOnFire(3, false)
                    }
                    if (["minecraft:guardian", "minecraft:elder_guardian", "minecraft:witch"].includes(aboveEntity.typeId)) {
                        aboveEntity.runCommand("damage @s 10 entity_attack")
                    } else {
                        aboveEntity.runCommand("damage @s 10 entity_attack entity @s")
                    }
                }
            }
        }
    }

    getExperienceValue(typeId) {
        for (const category in this.XP_DROPS) {
            for (const value in this.XP_DROPS[category]) {
                if (this.XP_DROPS[category][value].includes(typeId)) {
                    return parseInt(this.getRandomInteger(value.split('-')[0], value.split('-')[1]));
                }
            }
        }
        return 0; // Si aucune correspondance n'est trouvée
    }

    getRandomInteger(min, max) {
        // Assurer que min est toujours le plus petit des deux
        min = Math.ceil(min);
        max = Math.floor(max);

        // Calculer un nombre aléatoire entre min et max inclus
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    loadIgnoredEntities(block) {
        const data = world.getDynamicProperty(`pb_red:IgnoredEntities:${block}`);
        if (data) {
            return JSON.parse(data);
        }
        return [];
    }
}

