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

const LEAF_TYPES = {
    oak: {
        component: "ecbl_bc:replace_oak_leaves_with_custom",
        remover: "ecbl_bc:oak_leaves_remover",
        leaveSet: ['minecraft:oak_leaves'],
        result: "ecbl_bc:oak_leaves_green"
    },
    birch: {
        component: "ecbl_bc:replace_birch_oak_leaves_with_custom",
        remover: "ecbl_bc:birch_leaves_remover",
        leaveSet: ['minecraft:oak_leaves', 'minecraft:birch_leaves'],
        result: "ecbl_bc:birch_leaves"
    },
    birchOakRemove: {
        component: "ecbl_bc:birch_oak_remover",
        remover: "ecbl_bc:birch_oak_remover",
        leaveSet: ['minecraft:oak_leaves', 'minecraft:birch_leaves', 'minecraft:oak_log', 'minecraft:birch_log', 'minecraft:mushroom_stem', 'minecraft:red_mushroom_block', 'minecraft:brown_mushroom_block'],
        result: "minecraft:air"
    },
    onlyBirch: {
        component: "ecbl_bc:replace_birch_leaves_with_custom",
        remover: "ecbl_bc:birch_leaves_remover",
        leaveSet: ['minecraft:birch_leaves'],
        result: "ecbl_bc:birch_leaves"
    },
    spruce: {
        component: "ecbl_bc:replace_spruce_with_air",
        remover: "ecbl_bc:spruce_remover",
        leaveSet: ['minecraft:spruce_leaves', 'minecraft:spruce_log'],
        result: "minecraft:air"
    },
    acacia: {
        component: "ecbl_bc:replace_acacia_with_air",
        remover: "ecbl_bc:acacia_remover",
        leaveSet: ['minecraft:acacia_leaves', 'minecraft:acacia_log'],
        result: 'minecraft:air'
    }
};

/**
 * 
 * @param {BlockComponentTickEvent} e 
 * @param {*} config 
 */
function handleLeafReplacement(e, config) {
    const { block: initialBlock, dimension } = e;
    const { x, y, z } = initialBlock.location;

    const toRemove = new Set([...config.leaveSet, config.remover]);
    const positions = [
        { x: x + 1, y, z }, { x: x - 1, y, z },
        { x, y: y + 1, z }, { x, y: y - 1, z },
        { x, y, z: z + 1 }, { x, y, z: z - 1 }
    ];

    if (positions.every(pos => {
        const block = dimension.getBlock(pos);
        if (!block) return false;
        if (toRemove.has(block.typeId) && block.typeId !== config.remover) {
            block.setType(config.remover);
        }
        return true;
    })) {
        initialBlock.setType(config.result);
    }
}

world.beforeEvents.worldInitialize.subscribe((Initiate) => {
    Object.values(LEAF_TYPES).forEach(config => {
        Initiate.blockComponentRegistry.registerCustomComponent(config.component, {
            onTick: (e) => handleLeafReplacement(e, config)
        });
    });
});