import { Direction } from "@minecraft/server";
import { SuppStates } from "../reg/suppStates";
import { suppEvents } from "../suppEventHandler";
import { flipDir, getADirection, getADirectionState, getClockwiseDir, getClosestDir, getCounterClockwiseDir, isSameAxis, offsetPos, setADirectionState } from "../util/dirUtils";
import { McBlocks } from "../reg/mcBlocks";
export const IronGateComponent = {
    onPlayerInteract(event) {
        const block = event.block;
        const opened = block.permutation.getState(SuppStates.Open);
        let perm = block.permutation.withState(SuppStates.Open, !opened);
        let myDir = getADirection(block);
        if (event.player) {
            const yaw = event.player.getRotation().y;
            myDir = flipDir(getClosestDir(yaw, [myDir, flipDir(myDir)]));
            perm = setADirectionState(perm, myDir);
        }
        block.setPermutation(perm);
        let above = block.above();
        while (above && above.typeId == block.typeId && isSameAxis(myDir, getADirection(above))) {
            above.setPermutation(setADirectionState(above.permutation.withState(SuppStates.Open, !opened), myDir));
            above = above.above();
        }
        let below = block.below();
        while (below && below.typeId == block.typeId && isSameAxis(myDir, getADirection(below))) {
            below.setPermutation(setADirectionState(below.permutation.withState(SuppStates.Open, !opened), myDir));
            below = below.below();
        }
        event.dimension.playSound(opened ? "close.iron_trapdoor" : "open.iron_trapdoor", block.center());
    },
    beforeOnPlayerPlace(event) {
        const block = event.block;
        const above = block.above();
        const perm = event.permutationToPlace;
        if (above && above.typeId == perm.type.id &&
            isSameAxis(getADirection(above), getADirectionState(perm))) {
            event.permutationToPlace = perm.withState(SuppStates.Connected, true);
        }
    }
};
suppEvents.subscribeOnNeighborChanged((event) => {
    const block = event.block;
    if (block.typeId == "razz_sup:iron_gate" /* SuppBlocks.IronGate */) {
        if (event.fromDir == Direction.Up || !isSameAxis(getADirection(block), event.fromDir)) {
            const perm = block.permutation.withState(SuppStates.Connected, shouldBeConnected(block));
            block.setPermutation(perm);
        }
    }
});
function shouldBeConnected(block) {
    const myDir = getADirection(block);
    const above = block.above();
    const left = offsetPos(block, getClockwiseDir(myDir));
    const right = offsetPos(block, getCounterClockwiseDir(myDir));
    return (above && above.typeId == block.typeId &&
        isSameAxis(myDir, getADirection(above)))
        || (left && left.typeId == McBlocks.IronBars)
        || (right && right.typeId == McBlocks.IronBars);
}
