import { world, EquipmentSlot, EntityEquippableComponent, system } from '@minecraft/server';

world.beforeEvents.itemUseOn.subscribe((eventData) => {
    const block = eventData.block;
    const player = eventData.source;
    const blockPermutations = block.permutation.getAllStates();
    const mainhand = player.getComponent(EntityEquippableComponent.componentId).getEquipmentSlot(EquipmentSlot.Mainhand);
    const item = mainhand.getItem();
    const dimension = block.dimension;

    if (mainhand?.hasTag("furnideco:paint_brush")) {
        if (blockPermutations.hasOwnProperty('furnideco:color')) {
            let currentColorValue = blockPermutations['furnideco:color'];

            let newColorValue;
            if (block.typeId.includes("chair") || block.typeId.includes("vase")) {
                newColorValue = currentColorValue === 7 ? 0 : currentColorValue + 1;
            } else if (block.typeId.includes("stool") || block.typeId.includes("sofa") || block.typeId.includes("curtain")) {
                newColorValue = currentColorValue === 15 ? 0 : currentColorValue + 1;
            } else {
                newColorValue = currentColorValue === 7 ? 0 : currentColorValue + 1;
            }

            let newPermutation = block.permutation.withState('furnideco:color', newColorValue);
            system.run(() => {
                block.setPermutation(newPermutation);
                mainhand.setItem(reduceDurability(player, item, 1));
                player.playSound("furnideco.paint", { location: block });
                dimension.spawnParticle("furnideco:paint", { x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 });
            });
        }
    }
});


function reduceDurability(player, item, reduceAmount, finalItem = null, breakSound = "random.break", finalItemSound = null) {
    if (player.getGameMode() === "creative") return item;
    const comp = item.getComponent(ItemDurabilityComponent.componentId);
    if (!comp) return item;
    const unbreakingLevel = getRelevantEnchantment(item, "unbreaking");
    const chanceToAvoidDamage = unbreakingLevel > 0 ? unbreakingLevel / (unbreakingLevel + 1) : 0;
    console.log("Unbreaking Level:", unbreakingLevel, "Chance to avoid damage:", chanceToAvoidDamage);
    if (Math.random() < chanceToAvoidDamage) {
        return item;
    }
    const reducedAmount = reduceAmount + comp.damage;
    if (reducedAmount >= comp.maxDurability) {
        if (finalItem) {
            if (finalItemSound) {
                world.playSound(finalItemSound, player.location);
            }
            return finalItem;
        }
        world.playSound(breakSound, player.location);
        return undefined;
    }
    comp.damage = reducedAmount;
    return item;
}