import { Entity, EquipmentSlot, ItemStack, Player, world, system, Block } from "@minecraft/server";

/**
 * 
 * @param {Player} player 
 * @param {Entity} damaged
 * @param {ItemStack} item 
 * @param {EquipmentSlot} equippable 
 */
export function captureMob(player, damaged, item, equippable) {
    const mobType = item?.getLore()[2];

    if (mobType === undefined && !damaged.typeId.startsWith(`cy_cr:`)) {
        item.setLore([`${item.getLore()[0]}`, `${item.getLore()[1]}`, ``, `§7Captured mob: ${damaged.typeId}`, `§7Mob Id: ${damaged.id}`]);
        equippable.setEquipment("Mainhand", item);
        world.structureManager.createFromWorld(`cy_cr:${damaged.id}_saved_mob`, player.dimension, damaged.location, damaged.location, { includeEntities: true })
        damaged?.remove();
        player.setDynamicProperty(`cy_cr:canUse`, true);
    } else return;
};
/**
 * 
 * @param {Player} player 
 * @param {ItemStack} item
 * @param {Block} block 
 */
export function releaseMob(player, item, block) {
    const itemLore = item.getLore();
    const canUse = player.getDynamicProperty(`cy_cr:canUse`);

    if (canUse === true && itemLore.length > 2) {
        player.setDynamicProperty(`cy_cr:canUse`, false);

        const id = itemLore[4].split(' ')[2];
        const equippable = player.getComponent("equippable");

        const run = system.run(() => {
            system.clearRun(run);
            const structure = world.structureManager.get(`cy_cr:${id}_saved_mob`);
            world.structureManager.place(structure, player.dimension, { x: block.location.x + 0.5, y: block.location.y + 1, z: block.location.z + 0.5 });
            item.setLore(["§7You can trap mobs by hitting them and release it", "§7again by interacting on a farm or a block"]);
            equippable.setEquipment("Mainhand", item)
        });

        system.runTimeout(() => {
            player.setDynamicProperty(`cy_cr:canUse`, true);
        }, 2)
    } else return;
}