import { world } from '@minecraft/server';

world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {

    itemComponentRegistry.registerCustomComponent('compycraft_era:durability', {
        onMineBlock(e) {
            const { itemStack, source } = e;
            const equippable = source.getComponent('equippable')
            try {
                itemStack.getComponent('durability').damage += 2
                equippable.setEquipment('Mainhand', itemStack)
            } catch (er) {
                equippable.setEquipment('Mainhand')
                source.playSound('random.break', { location: source.location })
            }
        },
        onBeforeDurabilityDamage(e) {
            if (100 / ((e.itemStack.getComponent('enchantable')?.getEnchantment('unbreaking')?.level || 0) + 1) >= Math.random() * 100) e.durabilityDamage = 1;
            else e.durabilityDamage = 0
        }
    })

})

world.afterEvents.itemUseOn.subscribe(event => {

    const { itemStack, source, block } = event;

    if (!itemStack.typeId.startsWith('compycraft') || !itemStack.hasTag('minecraft:is_axe')) return;

    if (!block.typeId.includes('wood') && !block.typeId.includes('log') && !block.typeId.includes('hyphae') && !block.typeId.includes('minecraft:')) return;

    source.playSound('use.wood', { location: block })
    const equippable = source.getComponent('equippable')

    if (source.getGameMode() == 'creative') return;

    try {
        itemStack.getComponent('durability').damage += 1
        equippable.setEquipment('Mainhand', itemStack)
    } catch (er) {
        equippable.setEquipment('Mainhand')
        source.playSound('random.break', { location: source.location })
    }

})