import { world, system, EquipmentSlot, ItemComponentTypes } from "@minecraft/server";

export function isWearingItem(player, slot, itemId) {
    const equipment = player.getComponent("minecraft:equippable");
    if (!equipment) return false;
    
    const itemStack = equipment.getEquipment(slot);
    return itemStack && itemStack.typeId === itemId;
}

export function damageItem(player, slot, damageAmount) {
    const equipment = player.getComponent("minecraft:equippable");
    if (!equipment) return;

    // Do not damage or break items in Creative mode
    if (player.getGameMode() === "creative") {
        return false;
    }

    const itemStack = equipment.getEquipment(slot);
    if (!itemStack) return;

    const durabilityComponent = itemStack.getComponent(ItemComponentTypes.Durability);
    if (durabilityComponent) {
        const newDamage = durabilityComponent.damage + damageAmount;
        if (newDamage >= durabilityComponent.maxDurability) {
            equipment.setEquipment(slot, undefined); // Remove item if it is broken
            return true;
        }
        else
        {
            durabilityComponent.damage = newDamage
            equipment.setEquipment(slot, itemStack);
            return false;
        }
    }
    return false;
}
