import { world, BlockPermutation, system } from "@minecraft/server";

system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:herbs_grow", {
        onRandomTick: e => {
            const { block, dimension } = e;

            const isSeed = block.permutation.getState("rustic:seed");

            if (!isSeed)return;

            if ( (Math.random() * 100) > 33 ) return;

            block.setPermutation(block.permutation.withState("rustic:seed", false));
        },
        beforeOnPlayerPlace: e => {
            const { permutationToPlace } = e;
            e.permutationToPlace = permutationToPlace.withState('rustic:seed', true);
        },
    });
});

world.beforeEvents.playerInteractWithBlock.subscribe((eventData) => {
    const { player, block, itemStack, isFirstEvent } = eventData;
    if (!isFirstEvent)return;
    if (!block.hasTag('rustic:herb'))return;
    if (itemStack == undefined) return;
    const isSeed = block.permutation.getState("rustic:seed");
    if (!isSeed)return;

    if (itemStack.typeId == 'minecraft:bone_meal'){
        system.run(() => {
            block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());
            block.dimension.playSound("item.bone_meal.use", block.center());
            const equipment = player.getComponent('equippable');
            if (player.getGameMode() !== "creative") {
                if (itemStack.amount > 1) {
                    itemStack.amount -= 1;
                    equipment.setEquipment('Mainhand', itemStack);
                } else if (itemStack.amount === 1) {
                    equipment.setEquipment('Mainhand', undefined);
                }
            }
            if ( (Math.random() * 100) > 60 ) return;
            block.setPermutation(block.permutation.withState("rustic:seed", false));
        })
    }
})