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

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

            const currentState = block.permutation.getState("r:stages");
            
            if(currentState == 0 || block.hasTag("MaxStage")) return;

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

            if (block.hasTag("preMaxStage") && block.above().hasTag("WoodenStake")){
                const aboveState = block.above().permutation.getState("r:stages");
                const cropState = block.permutation.getState("r:crop");
                
                if ( (cropState == 'tomato' && aboveState == 0 && (block.below().hasTag("fertile_soil") || block.below().below().hasTag("fertile_soil") || block.below().typeId == "minecraft:farmland" || block.below().below().typeId == "minecraft:farmland")) || (cropState == 'chili' && aboveState == 0 && (block.below().hasTag("fertile_soil") || block.below().typeId == "minecraft:farmland"))){
                    block.above().setPermutation(block.above().permutation.withState("r:stages", 1));
                    block.above().setPermutation(block.above().permutation.withState("r:crop", cropState));
                }
            }

            block.setPermutation(block.permutation.withState("r:stages", currentState + 1));
        },
    });
});

world.beforeEvents.playerInteractWithBlock.subscribe(eventData => {
    const block = eventData.block;
    const player = eventData.player;
    const dimension = block.dimension;

    if (!block.hasTag("WoodenStake") || !block.hasTag("MaxStage"))return;

    const firstStake = dimension.getBlockFromRay(block.center(),{x:0,y:-1,z:0},{excludeTags:["WoodenStake"]}).block
    
    let steps = 0;
    while (firstStake.above(steps+1)?.hasTag("WoodenStake")){
        steps++;
        if (!firstStake.above(steps)?.hasTag("MaxStage"))continue;
        const blockCopy = firstStake.above(steps);
        const cropName = firstStake.above(steps).permutation.getState("r:crop") == 'tomato' ? "tomato" : "chili_pepper"
        const crop = new ItemStack("rustic:" + cropName, 1)
        system.run( () => {
            player.dimension.spawnItem(crop,blockCopy.center())

            if ( (Math.random() * 100) < 50 ) {
                player.dimension.spawnItem(crop,blockCopy.center())
            }
            if ( (Math.random() * 100) < 5 ) {
                player.dimension.spawnItem(new ItemStack("rustic:poisonous_" + cropName, 1),blockCopy.center())
            }
            blockCopy.setPermutation(blockCopy.permutation.withState("r:stages", 4));
            
        })        
    }
    

    eventData.cancel = true
});