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

system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:lattice", {
        beforeOnPlayerPlace: e => {
            const { block, permutationToPlace } = e;
            const directions = {north: "south",south: "north",west: "east",east: "west",above: "above",below: "below",};
            const newStates = {};

            Object.entries(directions).forEach(([direction, opposite]) => {
                const adjacentBlock = block[direction]();
                if (isRelevantBlock(adjacentBlock)) {
                    if (adjacentBlock.hasTag("lattice")) {
                        if (direction == "above")direction = "below"
                        else if (direction == "below")direction = "above"
                        system.run(() => {adjacentBlock.setPermutation(adjacentBlock.permutation.withState(`r:${direction}`, true));})
                    }
                    newStates[`r:${opposite}`] = true;
                }
            });
            e.permutationToPlace = BlockPermutation.resolve(permutationToPlace.type.id,newStates)
        },
        onPlayerBreak: e => {
            const { player, block, dimension } = e;
            const directions = {north: "north",south: "south",west: "west",east: "east",above: "below",below: "above",};
            Object.entries(directions).forEach(([dir, state]) => {
                const adjacent = block[dir]();
                if (adjacent.hasTag("lattice")) {
                    adjacent.setPermutation(adjacent.permutation.withState(`r:${state}`, false));
                }
            });
        },
    });
});


export const isRelevantBlock = (adjacentBlock) =>
    adjacentBlock.hasTag("lattice") ||
    (!adjacentBlock.isAir &&
        !adjacentBlock.hasTag("crop") &&
        !adjacentBlock.hasTag("plant") &&
        !adjacentBlock.hasTag("one_way_collidable") &&
        !adjacentBlock.hasTag("rail") &&
        !adjacentBlock.hasTag("snow") &&
        !adjacentBlock.isLiquid &&
        !adjacentBlock.hasTag("text_sign") &&
        !adjacentBlock.hasTag("rustic:non_connectable")) &&
        adjacentBlock.typeId != "minecraft:short_grass" &&
        adjacentBlock.typeId != "minecraft:dandelion" &&
        adjacentBlock.typeId != "minecraft:poppy" &&
        adjacentBlock.typeId != "minecraft:blue_orchid" &&
        adjacentBlock.typeId != "minecraft:allium" &&
        adjacentBlock.typeId != "minecraft:azure_bluet" &&
        adjacentBlock.typeId != "minecraft:red_tulip" &&
        adjacentBlock.typeId != "minecraft:orange_tulip" &&
        adjacentBlock.typeId != "minecraft:cornflower";