import { world, ItemStack, GameMode } from '@minecraft/server';

const toolTypeIds = [
    'gs_ce:resin_pickaxe',
    'gs_ce:resin_axe',
    'gs_ce:resin_shovel'
];

const weaponTypeIds = [
    'gs_ce:resin_sword'
];

world.afterEvents.playerBreakBlock.subscribe(evd => {
    const { player, itemStackBeforeBreak: itemUsed } = evd;

    if (!itemUsed || player.matches({ gameMode: GameMode.creative })) return;

    if (toolTypeIds.includes(itemUsed.typeId) || weaponTypeIds.includes(itemUsed.typeId)) {
        const playerEquippableComp = player.getComponent("equippable");

        if (!playerEquippableComp) return;

        const itemEnchantmentComp = itemUsed.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 = itemUsed.getComponent("durability");

        if (!itemUsedDurabilityComp) return;

        let durabilityModifier = 0;
        if (toolTypeIds.includes(itemUsed.typeId)) {
            durabilityModifier = 1;
        } else {
            durabilityModifier = 2;
        }

        itemUsedDurabilityComp.damage += durabilityModifier;

        const maxDurability = itemUsedDurabilityComp.maxDurability
        const currentDamage = itemUsedDurabilityComp.damage
        if (currentDamage >= maxDurability) {

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

            playerEquippableComp.setEquipment("Mainhand", itemUsed);
        }
    }
})