import { world, BlockPermutation, ItemStack, system } from "@minecraft/server";
import { attemptToInventory } from "../functions";

system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:wildberry_bush", {
        onRandomTick: e => {
            const { block, dimension } = e;
            const growState = block.permutation.getState("r:berries");

            if ( growState ) return;

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

            block.setPermutation(block.permutation.withState("r:berries", !growState));
        },
        onPlayerInteract: e => {
            const { player, block, dimension, face, faceLocation } = e;
            const item = player.getComponent('inventory').container.getItem(player.selectedSlotIndex);
            const growState = block.permutation.getState("r:berries");

            if ( !growState ){
                if (item == undefined) return;
                if (item.typeId != 'minecraft:bone_meal') return;

                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 (item.amount > 1) {
                        item.amount -= 1;
                        equipment.setEquipment('Mainhand', item);
                    } else if (item.amount === 1) {
                        equipment.setEquipment('Mainhand', undefined);
                    }
                }
                block.setPermutation(block.permutation.withState("r:berries", !growState));
            }
            else if ( growState ) {
                block.setPermutation(block.permutation.withState("r:berries", !growState));
                attemptToInventory(player,new ItemStack("rustic:wildberries"),block.center(),dimension);
                dimension.playSound("block.sweet_berry_bush.pick",block.center(),{pitch:1.2})
            }
        },
        onTick: e => {
            const { block, dimension } = e;
            const isPlacedByPlayer = block.permutation.getState("r:firstGrow");
            if (isPlacedByPlayer) return;
            if (block.typeId == "minecraft:air") return;
            block.setPermutation(block.permutation.withState("r:berries", true));
            block.setPermutation(block.permutation.withState("r:firstGrow", true));
        },
        onPlayerBreak: e => {
            const { player, block, dimension, brokenBlockPermutation } = e;
            if(player.getGameMode() == "Creative" ) return;

            const growStage = brokenBlockPermutation.getState("r:berries")

            if ( !growStage ) return;

            dimension.spawnItem(new ItemStack("rustic:wildberries"), block.center());
        }


    });
});