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

const has_amount = {
    onPlayerInteract(event) {
        const block = event.block;
        const player = event.player;
        const blockPermutations = block.permutation.getAllStates();
        const mainhand = player.getComponent(EntityEquippableComponent.componentId).getEquipmentSlot(EquipmentSlot.Mainhand);
        const item = mainhand.getItem();
        if (item?.typeId == "furnideco:rustic.book") {
            if (blockPermutations.hasOwnProperty('furnideco:books')) {
                let currentBookValue = blockPermutations['furnideco:books'];
                if (currentBookValue === 4) {
                    return;
                }
                let newBookValue = currentBookValue + 1;
                let newPermutation = block.permutation.withState('furnideco:books', newBookValue);
                system.run(() => {
                    block.setPermutation(newPermutation);
                    mainhand.setItem(reduceStack(player, item));
                    player.playSound("furnideco.book.stack", { location: block });
                    block.dimension.spawnParticle("furnideco:dust", {
                        x: block.location.x + 0.5,
                        y: block.location.y + 0.5,
                        z: block.location.z + 0.5,
                    });
                });
            }
        } else if (item?.typeId == "furnideco:rustic.bottle") {
            if (blockPermutations.hasOwnProperty('furnideco:bottles')) {
                let currentbottleValue = blockPermutations['furnideco:bottles'];
                if (currentbottleValue === 2) {
                    return;
                }
                let newbottleValue = currentbottleValue + 1;
                let newPermutation = block.permutation.withState('furnideco:bottles', newbottleValue);
                system.run(() => {
                    block.setPermutation(newPermutation);
                    mainhand.setItem(reduceStack(player, item));
                    player.playSound("furnideco.bottle.stack", { location: block });
                    block.dimension.spawnParticle("furnideco:dust", {
                        x: block.location.x + 0.5,
                        y: block.location.y + 0.5,
                        z: block.location.z + 0.5,
                    });
                });
            }
        }
    }
};

world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent(
        "furnideco:has_amount",
        has_amount
    );
});

function reduceStack(player, item) {
    if (player.getGameMode() === "creative") return item;
    if (item.amount > 1) {
        item.amount -= 1;
        return item;
    } else {
        return undefined;
    }
}
