import { world, system, ItemStack } from "@minecraft/server"
import { killMarriedplayer, findMarried } from "../items/artifacts/soulbound_ring.js"
import { CaretakerDie, BondlingLink } from "./runic_mobs.js";

world.afterEvents.entityDie.subscribe(({ deadEntity }) => {
    //try {
    if (deadEntity?.dimension == undefined) return;
    const position = deadEntity?.location
    const dimension = deadEntity?.dimension
    if (deadEntity.typeId == "edx:player_soul") {
        dimension.spawnParticle("edx:soul_explosion", deadEntity.getHeadLocation());
    }
    if (deadEntity.typeId == "edx:spark_plug") {
        const block = deadEntity.dimension.getBlockFromRay({ x: deadEntity.location.x, y: deadEntity.location.y, z: deadEntity.location.z }, { x: 0, y: -1, z: 0 }, { maxDistance: 10 })?.block
        if (block?.above()?.typeId == "minecraft:air") {
            block.above().setType('edx:spark_plug_block')
        }

    }
    else if (deadEntity.typeId == "edx:behemoth") {
        const entityOptions1 = {
            location: deadEntity.location,
            type: "edx:behemoth",
            maxDistance: 30
        }
        const entities1 = deadEntity.dimension.getEntities(entityOptions1);
        if (entities1 != undefined)
            for (let i = 0; i < entities1.length; i++) {
                const entity = entities1[i]
                entity.triggerEvent('enrage')
            }
    }
    if (deadEntity.typeId == "minecraft:player") {
        PlayerSoul(deadEntity)
        deadEntity.setDynamicProperty('blazeblade_arena', undefined)
        if (deadEntity.hasTag('soulbound_ring')) {
            var marriedPlayer = findMarried(deadEntity)
            if (marriedPlayer != undefined) {
                killMarriedplayer(marriedPlayer, deadEntity)
            }
        }

    }
    else if (deadEntity?.getProperty('edx:is_chested')) {
        const entityOptions = {
            type: "minecraft:item",
            location: deadEntity.location,
            maxDistance: 2
        }
        const entities = dimension.getEntities(entityOptions);
        for (let i = 0; i < entities.length; i++) {
            const entity = entities[i]
            var item = entity?.getComponent("minecraft:item")?.itemStack
            if (item.typeId == "minecraft:chest") {
                entity.remove()
                return
            }
        }
    }

    else if (deadEntity.typeId == "edx:bondling") {
        BondlingLink(deadEntity)
    }
    else if (deadEntity.typeId == "edx:caretaker") {
        CaretakerDie(deadEntity)
    }

    else if (deadEntity.typeId === 'edx:abomination2') {
        world.setDynamicProperty("hard_mode", 1)
        dimension.runCommand(`scoreboard players add * difficulty 1`)
        dimension.runCommand(`particle edx:abomination_death ${position.x} ${position.y} ${position.z}`)
        const entityOptions = {
            location: position,
            families: ["player"],
            maxDistance: 50
        }
        const entities = dimension.getEntities(entityOptions);
        for (let i = 0; i < entities.length; i++) {
            var chance = Math.random()
            if (chance < 0.5)
                dimension.spawnItem(new ItemStack('edx:xp_orb', 1), entities[i].location);
            else
                dimension.spawnItem(new ItemStack('edx:magic_axe', 1), entities[i].location);
            if (!entities[i].hasTag('abom')) {
                entities[i].runCommand(`scoreboard players add @s max_health 4`)
                var abomMessage = {
                    rawtext: [{
                        translate: "message.event.abom",
                    }]
                };
                entities[i].sendMessage(abomMessage)
                entities[i].addTag('abom')
            }

        }
    }
    //wither is in after hit bc of his anim
    else if (deadEntity.typeId === 'minecraft:ender_dragon') {
        world.setDynamicProperty("void_mode", 1)
        dimension.runCommand(`scoreboard players add * difficulty2 1`)
        const entityOptions = {
            location: position,
            families: ["player"],
            maxDistance: 100
        }
        const entities = dimension.getEntities(entityOptions);
        for (let i = 0; i < entities.length; i++) {
            entities[i].runCommand(`scoreboard players add @s[tag=!dragon] max_health 4`)
            entities[i].addTag('dragon')
            dimension.spawnItem(new ItemStack('edx:dragon_heart', 1), entities[i].location);
            dimension.spawnItem(new ItemStack('edx:dragon_essence', 1), entities[i].location);

        }
    }
    else if (deadEntity.typeId === 'edx:true_wither') {
        const entityOptions = {
            location: position,
            families: ["player"],
            maxDistance: 50
        }
        const entities = dimension.getEntities(entityOptions);
        for (let i = 0; i < entities.length; i++) {
            entities[i].runCommand(`scoreboard players add @s[tag=!true_wither] max_health 4`)
            entities[i].addTag('true_wither')

        }
    }
    else if (deadEntity.typeId === 'edx:blazeblade2') {
        const arena = world.getEntity(deadEntity.getDynamicProperty('id'))
        arena.dimension.spawnEntity('edx:blazeblade_dead', arena.location)
        arena.remove()
        const entityOptions = {
            location: position,
            families: ["player"],
            maxDistance: 50
        }
        const entities = dimension.getEntities(entityOptions);
        for (let i = 0; i < entities.length; i++) {
            dimension.spawnItem(new ItemStack('edx:blaze_blade', 1), entities[i].location);
            dimension.spawnItem(new ItemStack('edx:explosive_blaze_rod', 1), entities[i].location);
            entities[i].runCommand(`scoreboard players add @s[tag=!blazeblade] max_health 4`)
            entities[i].addTag('blazeblade')
            entities[i].setDynamicProperty('blazeblade_arena', undefined)
        }

    }
    else if (deadEntity.typeId === 'edx:soul_blazeblade2') {
        const arena = world.getEntity(deadEntity.getDynamicProperty('id'))
        arena.dimension.spawnEntity('edx:blazeblade_dead', arena.location)
        arena.remove()
        const entityOptions = {
            location: position,
            families: ["player"],
            maxDistance: 50
        }
        const entities = dimension.getEntities(entityOptions);
        for (let i = 0; i < entities.length; i++) {
            dimension.spawnItem(new ItemStack('edx:soul_dashing_stick', 1), entities[i].location);
            dimension.spawnItem(new ItemStack('edx:explosive_blaze_rod', 1), entities[i].location);//efosi change 
            entities[i].runCommand(`scoreboard players add @s[tag=!soul_blazeblade] max_health 4`)
            entities[i].addTag('soul_blazeblade')
            entities[i].setDynamicProperty('blazeblade_arena', undefined)
        }

    }
    //}
    //catch(e){}



})


function PlayerSoul(player) {
    if (world.getDynamicProperty("player_soul") == false) return;
    var dropChance = 1;
    if (player.dimension.getBlock(player.location).typeId == "minecraft:lava")
        dropChance = 1 / 3;
    var hasWeapon = false;
    var hasHelmet = false;
    var hasChestplate = false;
    const soul = player.dimension.spawnEntity("edx:player_soul", player.location);
    const can_attack_player = world.getDynamicProperty('player_soul_attack')
    const can_wear_equipment = world.getDynamicProperty('player_soul_equipment')
    if (can_attack_player == false)
        soul.triggerEvent("no_AI");
    const entityOptions = {
        type: "minecraft:item",
        location: player.location,
        maxDistance: 8
    };
    const inv = soul?.getComponent("minecraft:inventory")?.container;
    const entities = player.dimension.getEntities(entityOptions);
    soul.nameTag = player.name;
    for (let i = 0; i < entities.length && i < 63; i++) {
        const entity = entities[i];
        var item = entity?.getComponent("minecraft:item")?.itemStack;
        if (
            Math.random() <= dropChance ||
            item.typeId.toLowerCase().includes("void") ||
            item.typeId.toLowerCase().includes("light") ||
            item.typeId.toLowerCase().includes("netherite") ||
            item.hasTag('artifact')
        ) {
            inv.addItem(item);
            if (can_wear_equipment == undefined || can_wear_equipment == true) {
                if (
                    (hasWeapon == false && (item.typeId.toLowerCase().includes("sword")) ||
                        item.typeId.toLowerCase().includes("armblade") ||
                        item.typeId.toLowerCase().includes("spear"))
                ) {
                    soul.runCommand(
                        `replaceitem entity @s slot.weapon.mainhand 0 ${item.typeId}`
                    );
                    hasWeapon = true;
                } else if (
                    hasWeapon == false && item.typeId.toLowerCase().includes("bow") &&
                    !item.typeId.toLowerCase().includes("crossbow") &&
                    !item.typeId.toLowerCase().includes("bowl")
                ) {
                    soul.runCommand(
                        `replaceitem entity @s slot.weapon.mainhand 0 ${item.typeId}`
                    );
                    soul.triggerEvent("ranged");
                    hasWeapon = true;
                } else if (hasHelmet == false && item.typeId.includes("elmet")) {
                    soul.runCommand(
                        `replaceitem entity @s slot.armor.head 0 ${item.typeId}`
                    );
                    hasHelmet = true;
                } else if (hasChestplate == false && item.typeId.includes("hestplate")) {
                    soul.runCommand(
                        `replaceitem entity @s slot.armor.chest 0 ${item.typeId}`
                    );
                    hasChestplate = true;
                }
            }
        }
        entity.remove();
    }
}