// Import necessary modules from Minecraft server API
import { world } from '@minecraft/server';

const table_connection = {
    onTick(e) {
        // Destructure event data for easier access
        const { block } = e;

        // Get adjacent blocks
        const north = block.north();
        const east = block.east();
        const south = block.south();
        const west = block.west();

        // Define an array of block types to exclude from connections
        const excludeBlocksArray = [
            'minecraft:air',
            'minecraft:wooden_door',
            'minecraft:iron_door',
            'minecraft:acacia_door',
            'minecraft:birch_door',
            'minecraft:crimson_door',
            'minecraft:dark_oak_door',
            'minecraft:jungle_door',
            'minecraft:oak_door',
            'minecraft:spruce_door',
            'minecraft:warped_door',
            'minecraft:mangrove_door',
            'minecraft:cherry_door',
            'minecraft:bamboo_door',
            'minecraft:iron_trapdoor',
            'minecraft:acacia_trapdoor',
            'minecraft:birch_trapdoor',
            'minecraft:crimson_trapdoor',
            'minecraft:dark_oak_trapdoor',
            'minecraft:jungle_trapdoor',
            'minecraft:oak_trapdoor',
            'minecraft:spruce_trapdoor',
            'minecraft:warped_trapdoor',
            'minecraft:mangrove_trapdoor',
            'minecraft:cherry_trapdoor',
            'minecraft:bamboo_trapdoor',
            'minecraft:trapdoor',
            'minecraft:glass',
            'minecraft:glass_pane'
            // Add other block types you want to exclude
        ];

        // Check if the adjacent block is not in the excludeBlocksArray
        const northConnects = !excludeBlocksArray.includes(north?.typeId);
        const eastConnects = !excludeBlocksArray.includes(east?.typeId);
        const southConnects = !excludeBlocksArray.includes(south?.typeId);
        const westConnects = !excludeBlocksArray.includes(west?.typeId);

        // Update block states based on the presence of adjacent blocks
        block.setPermutation(block.permutation.withState('furnideco:north_picket', northConnects ? 1 : 0));
        block.setPermutation(block.permutation.withState('furnideco:south_picket', southConnects ? 1 : 0));
        block.setPermutation(block.permutation.withState('furnideco:east_picket', eastConnects ? 1 : 0));
        block.setPermutation(block.permutation.withState('furnideco:west_picket', westConnects ? 1 : 0));
    }
};

world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent(
        "furnideco:table_connection",
        table_connection
    );
});
