import { EntityComponentTypes, ItemComponentTypes, ItemStack, Player, system } from "@minecraft/server";
import { getGamemode } from "../../../library/worldFuntions";
import { isTool } from "../../../library/itemManager";

/**
 * Intercambia el item de la mano del jugador por otro item igual en el inventario
 * si el item de la mano se rompe.
 * @param {Player} player 
 */
export const breakToolSwitcherEvent = (player) => {
    if (!player.getDynamicProperty('nps_ec:tool_switcher')) return

    const equipament = player.getComponent(EntityComponentTypes.Equippable);

    const hand = equipament.getEquipment("Mainhand");

    if (hand != null) {
        if (isTool(hand)) {
            const durability = hand.getComponent(ItemComponentTypes.Durability);
            if (durability.damage >= durability.maxDurability) {
                system.runTimeout(() => {
                    try {
                        const gamemode = getGamemode(player);
                        if (gamemode === 'survival' || gamemode === 'adventure') {
                            for (let i = 0; i < player.getComponent(EntityComponentTypes.Inventory).container.size; i++) {
                                const item = player.getComponent(EntityComponentTypes.Inventory).container.getItem(i);
                                if (item != null && player.selectedSlotIndex !== i) {
                                    if (item.typeId === hand.typeId) {
                                        player.runCommand(`playsound random.break @s ~ ~ ~ 0.3`);
                                        player.getComponent(EntityComponentTypes.Inventory).container.setItem(player.selectedSlotIndex, item);
                                        player.getComponent(EntityComponentTypes.Inventory).container.setItem(i, null);
                                        break;
                                    }
                                }
                            }
                        }
                    } catch { }
                }, 1)
            }
        }
    }
}