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

const plant_pot = {
    onPlayerInteract(event) {
        const block = event.block;
        const dimension = block.dimension;
        const player = event.player;
        const { x, y, z } = block.location;
        const blockPermutations = block.permutation.getAllStates();
        const mainhand = player.getComponent(EntityEquippableComponent.componentId).getEquipmentSlot(EquipmentSlot.Mainhand);
        const item = mainhand.getItem();
        const plants = ["minecraft:cactus", "minecraft:sweet_berries", "minecraft:bamboo", "minecraft:deadbush", "minecraft:torchflower"];

        if (blockPermutations.hasOwnProperty('furnideco:plant')) {
            let currentPlantValue = blockPermutations['furnideco:plant'];

            if (currentPlantValue !== 0 && player.isSneaking && !plants.includes(item?.typeId)) {
                let loot = "";
                switch (currentPlantValue) {
                    case 1: loot = "cactus"; break;
                    case 2: loot = "sweet_berries"; break;
                    case 3: loot = "bamboo"; break;
                    case 4: loot = "deadbush"; break;
                    case 5: loot = "torchflower"; break;
                }
                if (loot) {
                    dimension.runCommandAsync(`loot spawn ${x + 0.5} ${y + 0.75} ${z + 0.5} loot ${loot}`);
                    player.playSound("block.sweet_berry_bush.break", { location: block });
                    dimension.spawnParticle("furnideco:dust", { x: x + 0.5, y: y + 0.25, z: z + 0.5 });
                    let newPermutation = block.permutation.withState('furnideco:plant', 0);
                    system.run(() => {
                        block.setPermutation(newPermutation);
                        mainhand.setItem(reduceStack(player, item));
                    });
                }
            }

            if (currentPlantValue === 0 && !player.isSneaking && plants.includes(item?.typeId)) {
                let newPermutation = block.permutation.withState('furnideco:plant', plants.indexOf(item.typeId) + 1);
                player.playSound("block.sweet_berry_bush.place", { location: block });
                dimension.spawnParticle("furnideco:green_sparkles", { x: x + 0.5, y: y + 0.25, z: z + 0.5 });
                system.run(() => {
                    block.setPermutation(newPermutation);
                    mainhand.setItem(reduceStack(player, item));
                });
            }
        }
    }
};

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

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