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

/**
 * Evento del componente cableSignalComponent
 * @param {{block: Block, dimension: Dimension}} event 
 */
export const cableSignalEvent = ({ 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:${powerLevel - 1}`) ||
                    findNeighborWithMatchingTag(block, 'power')
                );
                if (condition) {
                    if (checkAnyNeighborHasTag(block, 'power') && powerLevel === 1) {
                        if (findNeighborWithMatchingTag(block, 'power')) {
                            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')
            if (condition) {
                permutation = permutation.withState('nps_ec:power', 0);
            }
        } else {
            const powerLevel = permutation.getState('nps_ec:power');
            const condition = !checkAnyNeighborHasTag(block, `power:${powerLevel - 1}`)
            if (condition) {
                permutation = permutation.withState('nps_ec:power', 0);
            }
        }

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