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

world.beforeEvents.worldInitialize.subscribe((event) => {

    event.blockComponentRegistry.registerCustomComponent('ecbl_bc:owl_nest', {

        onRandomTick: (event) => {
            const blockLoc = event.block.location;
            const block = event.block;
            if (world.getTimeOfDay() > 12000 && world.getTimeOfDay() < 23000) {
                if (event.block.permutation.getState('ecbl_bc:has_owl')) {
                    start: for (let x = -1; x <= 1; x++) {
                        for (let z = -1; z <= 1; z++) {
                            const newBlockLoc = { x: blockLoc.x + x, y: blockLoc.y, z: blockLoc.z + z };
                            const newBlock = block.dimension.getBlock(newBlockLoc);
                            if (newBlock.typeId === "minecraft:air") {
                                block.dimension.spawnEntity("ecbl_bc:owl", newBlockLoc);
                                event.block.setPermutation(event.block.permutation.withState('ecbl_bc:has_owl', false))
                                break start;
                            }
                        }
                    }
                }
            }
        },
        onTick: (e) => {
            if (e.block.typeId === "ecbl_bc:owl_nest") {
                e.dimension.runCommand(`summon ecbl_bc:owl ${e.block.location.x + 1} ${e.block.location.y} ${e.block.location.z + 1}`);
            }
        },
        "onPlayerDestroy": (event) => {
            const blockLoc = event.block.location;
            const block = event.block;

            if (event.destroyedBlockPermutation.getState('ecbl_bc:has_owl')) {
                block.dimension.spawnEntity('ecbl_bc:owl', block.center)
            }

        }
    })
})