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

/**
 * Evento del componente plasmaBridgeWEComponent
 * @param {{block: Block, dimension: Dimension}} event
 */
export const plasmaBridgeWEEvent = ({ block, dimension }) => {
    try {
        if (block.typeId == 'nps_ec:plasma_bridge_west_east') {
            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_west_east`)
            }
        }
    } 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 resultWest = false;

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

    if (!resultWest) {
        if (blockNeighborWest !== undefined && blockNeighborWest.block.typeId == 'nps_ec:plasma_bridge_receiver') {
            if (blockNeighborWest.permutation.getState('minecraft:cardinal_direction') == 'east') {
                resultWest = true;
            }
        }
    }
    const resultEast = false;

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