import WBVector3 from '../../util/wbVector3';
function getOtherDoorOffset(cardinalDirection) {
    switch (cardinalDirection) {
        case 'north':
            return new WBVector3(-1, 0, 0);
        case 'east':
            return new WBVector3(0, 0, -1);
        case 'south':
            return new WBVector3(1, 0, 0);
        case 'west':
            return new WBVector3(0, 0, 1);
        default:
            throw new Error(`Unknown direction "${cardinalDirection}"`);
    }
}
function applyFnToDoor(block, fn) {
    fn(block);
    const isUpper = !!block.permutation.getState('twb_wisu:upper_block_bit');
    const otherBlock = isUpper ? block.below() : block.above();
    if (otherBlock && otherBlock.permutation.matches(block.typeId)) {
        fn(otherBlock);
    }
}
export default class DoorComponent {
    onPlayerInteract(e) {
        const openBit = !e.block.permutation.getState('twb_wisu:open_bit');
        e.block.dimension.playSound(openBit ? 'open.wooden_door' : 'close.wooden_door', e.block);
        applyFnToDoor(e.block, (block) => {
            block.setPermutation(block.permutation.withState('twb_wisu:open_bit', openBit));
        });
    }
    onPlace(e) {
        const cardinalDirection = e.block.permutation.getState('minecraft:cardinal_direction');
        const otherBlockOffset = getOtherDoorOffset(cardinalDirection);
        if (e.block.offset(otherBlockOffset)?.permutation.matches(e.block.typeId)) {
            const otherBlock = e.block.offset(otherBlockOffset.multiply(-1));
            if (!otherBlock || !otherBlock.permutation.matches(e.block.typeId)) {
                applyFnToDoor(e.block, (block) => {
                    block.setPermutation(block.permutation.withState('twb_wisu:door_hinge_bit', true));
                });
            }
        }
    }
}
