import { ItemStack } from "@minecraft/server";

export function toolDurability(player, hand) {
    if (player.getGameMode() === "creative") return;

    const playerEquippableComp = player.getComponent("minecraft:equippable");
    const itemStack = playerEquippableComp.getEquipment(hand);

    if (!playerEquippableComp) return;

    const itemEnchantmentComp = itemStack?.getComponent("minecraft:enchantable");
    const unbreakingLevel = itemEnchantmentComp?.getEnchantment("unbreaking")?.level ?? 0;
    const breakChance = 100 / (unbreakingLevel + 1);
    const randomizeChance = Math.random() * 100;

    if (breakChance < randomizeChance) return;

    const itemUsedDurabilityComp = itemStack?.getComponent("minecraft:durability");

    if (!itemUsedDurabilityComp) return;

    let durabilityModifier = 0;
    if (itemStack.typeId) {
        durabilityModifier = 1;
    } else {
        durabilityModifier = 2;
    }
    const maxDurability = itemUsedDurabilityComp.maxDurability;
    const currentDamage = itemUsedDurabilityComp.damage;
    
    if (currentDamage >= maxDurability) {

        player.playSound("random.break", { pitch: 1, location: player.location, volume: 1 });
        playerEquippableComp.setEquipment(hand, new ItemStack("minecraft:air", 1));
    }
    else if (currentDamage < maxDurability) {

        itemUsedDurabilityComp.damage += durabilityModifier;
        playerEquippableComp.setEquipment(hand, itemStack);
    }
};