import { Block, Dimension } from "@minecraft/server";

/**
 * Evento del componente plasmaBridgeNSComponent
 * @param {{block: Block, dimension: Dimension}} event
 */
export const plasmaBridgeNSEvent = ({ block, dimension }) => {
    try {
        if (block.typeId == 'nps_ec:plasma_bridge_north_south') {
            if (
                !plasmaBridgeCheckBlocks(dimension, block)
            ) {
                dimension.runCommand(`fill ${block.x} ${block.y} ${block.z} ${block.x} ${block.y} ${block.z} minecraft:air replace nps_ec:plasma_bridge_north_south`)
            }
        }
    } catch { }
}

/**
 * Escanea los bloques en un rango de 64 bloque para
 * encontrar un bloque de plasma bridge reciver
 * @param {Dimension} dimension 
 * @param {Block} block 
 * @param {string} face 
 * @returns {boolean}
 */
const plasmaBridgeCheckBlocks = (dimension, block) => {
    const resultNorth = false;

    const blockNeighborNorth = block.dimension.getBlockFromRay({ x: block.x, y: block.y, z: block.z+1 }, { x: 0, y: 0, z: 1 }, { maxDistance: 64, excludeTypes: ['minecraft:air', 'nps_ec:plasma_bridge_north_south', 'nps_ec:plasma_bridge_west_east'] })

    if (!resultNorth) {
        if (blockNeighborNorth !== undefined && blockNeighborNorth.block.typeId == 'nps_ec:plasma_bridge_receiver') {
            if (blockNeighborNorth.permutation.getState('minecraft:cardinal_direction') == 'south') {
                resultNorth = true;
            }
        }
    }

    const resultSouth = false;

    const blockNeighborSouth = block.dimension.getBlockFromRay({ x: block.x, y: block.y, z: block.z - 1 }, { x: 0, y: 0, z: -1 }, { maxDistance: 64, excludeTypes: ['minecraft:air', 'nps_ec:plasma_bridge_north_south', 'nps_ec:plasma_bridge_west_east'] })
    if (!resultSouth) {
        if (blockNeighborSouth.typeId == 'nps_ec:plasma_bridge_receiver') {
            if (blockNeighborSouth.permutation.getState('minecraft:cardinal_direction') == 'north') {
                resultSouth = true;
            }
        }
    }
    return (resultNorth && resultSouth);
}