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

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

            const water = surroundingWater(block);

            if ( !water ) return;

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

            const fertilizeState = block.permutation.getState("r:fertilize");

            if ( fertilizeState == 4 ) {
                block.setType("rustic:fertile_soil_ready")
                return;
            }
            block.setPermutation(block.permutation.withState("r:fertilize", fertilizeState + 1));
        }
    });
});

export function surroundingWater(block){
    if (block.north().typeId === "minecraft:water") return true;
    else if (block.south().typeId === "minecraft:water") return true;
    else if (block.east().typeId === "minecraft:water") return true;
    else if (block.west().typeId === "minecraft:water") return true;
    else if (block.north().east().typeId === "minecraft:water") return true;
    else if (block.north().west().typeId === "minecraft:water") return true;
    else if (block.south().east().typeId === "minecraft:water") return true;
    else if (block.south().west().typeId === "minecraft:water") return true;
    else if (block.north().north().typeId === "minecraft:water") return true;
    else if (block.south().south().typeId === "minecraft:water") return true;
    else if (block.east().east().typeId === "minecraft:water") return true;
    else if (block.west().west().typeId === "minecraft:water") return true;
    else if (block.east().east().south().typeId === "minecraft:water") return true;
    else if (block.east().east().north().typeId === "minecraft:water") return true;
    else if (block.east().east().south().south().typeId === "minecraft:water") return true;
    else if (block.east().east().north().north().typeId === "minecraft:water") return true;
    else if (block.west().west().south().typeId === "minecraft:water") return true;
    else if (block.west().west().north().typeId === "minecraft:water") return true;
    else if (block.west().west().south().south().typeId === "minecraft:water") return true;
    else if (block.west().west().north().north().typeId === "minecraft:water") return true;
    else if (block.north().north().east().typeId === "minecraft:water") return true;
    else if (block.north().north().west().typeId === "minecraft:water") return true;
    else if (block.south().south().east().typeId === "minecraft:water") return true;
    else if (block.south().south().west().typeId === "minecraft:water") return true;
    return false
}