import { suppEvents } from "../suppEventHandler";
import { Direction } from "@minecraft/server";
import { horizontalDirections, offsetPos, offsetVec } from "../util/dirUtils";
import { isBlockSolid } from "../util/miscUtils";
const PROPERTIES = new Map([
    [Direction.Up, "razz_sup:connection_up"],
    [Direction.North, "razz_sup:connection_north"],
    [Direction.East, "razz_sup:connection_east"],
    [Direction.South, "razz_sup:connection_south"],
    [Direction.West, "razz_sup:connection_west"]
]);
function getConnectionPerDirection(block, dir) {
    const p = block.getState(PROPERTIES.get(dir));
    return Object.values(Connection).find(value => value === p);
}
function updateConnection(perm, blockPos, fromDir, neighborBlock) {
    const solid = isBlockSolid(neighborBlock, fromDir);
    const oldConnection = getConnectionPerDirection(perm, fromDir);
    let conn = solid ? Connection.Short : Connection.None;
    const above = neighborBlock.dimension.getBlock(offsetVec(blockPos, Direction.Up));
    if (solid && above && above.typeId == "razz_sup:wicker_fence" /* SuppBlocks.WickerFence */) {
        const connection = getConnectionPerDirection(above.permutation, fromDir);
        if (connection != Connection.None) {
            conn = Connection.Tall;
        }
    }
    if (conn != oldConnection) {
        perm = perm.withState(PROPERTIES.get(fromDir), conn);
    }
    return perm;
}
suppEvents.subscribeOnNeighborChanged((event => {
    if (event.block.typeId == "razz_sup:wicker_fence" /* SuppBlocks.WickerFence */) {
        const oldPerm = event.block.permutation;
        const dir = event.fromDir;
        let perm;
        if (dir == Direction.Up) {
            for (const d of horizontalDirections) {
                let neighborBlock = offsetPos(event.block, d);
                if (neighborBlock) {
                    perm = updateConnection(oldPerm, event.block.location, d, neighborBlock);
                }
            }
        }
        else {
            perm = updateConnection(oldPerm, event.block.location, event.fromDir, event.neighborBlock);
        }
        if (perm != oldPerm) {
            event.block.setPermutation(perm);
        }
    }
}));
export const WickerFenceComponent = {
    beforeOnPlayerPlace(event) {
        const block = event.block;
        let perm = event.permutationToPlace;
        for (const d of horizontalDirections) {
            const neighbor = offsetPos(block, d);
            perm = updateConnection(perm, block.location, d, neighbor);
        }
        event.permutationToPlace = perm;
    }
};
var Connection;
(function (Connection) {
    Connection["None"] = "none";
    Connection["Short"] = "short";
    Connection["Tall"] = "tall";
})(Connection || (Connection = {}));
