import { blockNeighbors, checkAnyNeighborHasTag, findNeighborWithMatchingTag } from "../../library/blockManager";

/**
 * Evento del componente reinforcedCableSignalComponent
 * @param {{block: Block, dimension: Dimension}} event 
 */
export const reinforcedCableSignalEvent = ({ 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

        // Verificar y establecer el estado de energía
        if (permutation.getState('nps_ec:power') === 0) {
            for (let powerLevel = 1; powerLevel <= 15; powerLevel++) {
                const condition = checkAnyNeighborHasTag(block, `power:pure:${powerLevel - 1}`);
                if (condition) {
                    if(checkAnyNeighborHasTag(block, 'power:pure:0') && powerLevel === 1) {
                        if(findNeighborWithMatchingTag(block, 'power:pure:0')) {
                            permutation = permutation.withState('nps_ec:power', 1);
                            break;
                        }
                    } else {
                        permutation = permutation.withState('nps_ec:power', powerLevel);
                        break;
                    }
                }
            }
        } else if (permutation.getState('nps_ec:power') === 1)  {
            const condition = !findNeighborWithMatchingTag(block, `power:pure:0`);
            if (condition) {
                permutation = permutation.withState('nps_ec:power', 0);
            }
        } else {
            const powerLevel = permutation.getState('nps_ec:power')
            const condition = !checkAnyNeighborHasTag(block, `power:pure:${powerLevel - 1}`);
            if (condition) {
                permutation = permutation.withState('nps_ec:power', 0);
            }
        }

        block.setPermutation(permutation);
    } catch { }
}