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

system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:block_fruit", {
        onRandomTick: e => {
            const { block, dimension } = e;
            if (!block.hasTag("fruitBlock"))return;
            const fruitType = block.hasTag("melon_crop") ? "minecraft:melon_block" : "minecraft:pumpkin"
            
            let directions = [
                { dir: () => block.north(), growStage: 8 },
                { dir: () => block.east(), growStage: 5 },
                { dir: () => block.south(), growStage: 7 },
                { dir: () => block.west(), growStage: 6 }
            ];
            
            directions.sort(() => Math.random() - 0.5);
            
            for (let direction of directions) {
                if (direction.dir().isAir && direction.dir().below().isSolid) {
                    direction.dir().setType(fruitType);
                    block.setPermutation(block.permutation.withState("r:growStage", direction.growStage));
                    break;
                }
            }
        },
    });
});


world.beforeEvents.playerBreakBlock.subscribe(eventData => {
    const block = eventData.block;

    if (block.typeId != "minecraft:melon_block" && block.typeId != "minecraft:pumpkin")return;

    system.run( () => {
        if (block.north().permutation.getState("r:growStage") == 7)block.north().setPermutation(block.north().permutation.withState("r:growStage", 4));
        else if (block.east().permutation.getState("r:growStage") == 6)block.east().setPermutation(block.east().permutation.withState("r:growStage", 4));
        else if (block.south().permutation.getState("r:growStage") == 8)block.south().setPermutation(block.south().permutation.withState("r:growStage", 4));
        else if (block.west().permutation.getState("r:growStage") == 5)block.west().setPermutation(block.west().permutation.withState("r:growStage", 4));  
    })
})
