import { Block, Dimension } from "@minecraft/server";
import { blockNeighbors } from "../../library/blockManager";

/**
 * Evento del componente cableSignalComponent
 * @param {{block: Block, dimension: Dimension}} event 
 */
export const cableConnectionEvent = ({ block, dimension }) => {
    try{
        if(!block) return;
        const {
            blockNeighborUp, blockNeighborDown,
            blockNeighborEast, blockNeighborWest,
            blockNeighborNorth, blockNeighborSouth
        } = blockNeighbors(block);
    
        if(!blockNeighborUp || !blockNeighborDown ||
            !blockNeighborEast || !blockNeighborWest ||
            !blockNeighborNorth || !blockNeighborSouth) return;
    
        let permutation = block.permutation;

        if(block.typeId === 'minecraft:air') return
        
        if(block.typeId === 'nps_ec:clock_panel' || block.typeId === 'nps_ec:farmer') {
            const conditions = (
                    blockNeighborUp.hasTag('cable') || 
                    blockNeighborUp.hasTag('cable:up:down') ||
                    blockNeighborEast.hasTag('cable') ||
                    blockNeighborWest.hasTag('cable') ||
                    blockNeighborNorth.hasTag('cable') ||
                    blockNeighborSouth.hasTag('cable')
                )
            permutation = permutation.withState('nps_ec:down', conditions);
        }

        permutation = permutation.withState('nps_ec:up', (blockNeighborUp.hasTag('cable') || blockNeighborUp.hasTag('cable:up:down')));
        if(block.typeId !== 'nps_ec:clock_panel' && block.typeId !== 'nps_ec:farmer') permutation = permutation.withState('nps_ec:down', (blockNeighborDown.hasTag('cable') || blockNeighborDown.hasTag('cable:up:down')));
        permutation = permutation.withState('nps_ec:east', blockNeighborEast.hasTag('cable') || blockNeighborEast.hasTag('cable:west:east'));
        permutation = permutation.withState('nps_ec:west', blockNeighborWest.hasTag('cable') || blockNeighborWest.hasTag('cable:west:east'));
        permutation = permutation.withState('nps_ec:north', blockNeighborNorth.hasTag('cable') || blockNeighborNorth.hasTag('cable:north:south'));
        permutation = permutation.withState('nps_ec:south', blockNeighborSouth.hasTag('cable') || blockNeighborSouth.hasTag('cable:north:south'));
    
        block.setPermutation(permutation);
    } catch { }
}