import React from 'react';
import QBOrBlock from './QBOrBlock';
import QBAndBlock from './QBAndBlock';
import { QueryNodeElem, QueryNodeOp, QueryElem, isNodeElem, simplify } from '../../lib/query/Query';
import { QBQueryLeafElem } from './QBQueryLeafElem';
import { QBQueryElem } from './QBQueryElem';
import { O_APPEND } from 'constants';

export interface NodeProps {
    elem: QueryNodeElem,
    onReplace: (q: QueryElem | null) => void,
    editingQuery: boolean,
}

export function QBQueryNodeElem(props: NodeProps) {
    let e = props.elem;

    const onReplace = (idx: number, q: QueryElem | null) => {
        var ops = e.operands;
        if (q) {
            ops[idx] = q;
        } else {
            ops.splice(idx, 1);
        }
        let newNode = simplify({ operands: ops, nodeOp: e.nodeOp });
        props.onReplace(newNode);
    }

    const children = e.operands.map((o: any, idx: number) => {
        return <QBQueryElem
            elem={o}
            onReplace={(q: QueryElem | null) => onReplace(idx, q)}
            editingQuery={props.editingQuery}
        />
    });

    if (e.nodeOp == QueryNodeOp.And) {
        return <QBAndBlock>{children}</QBAndBlock>
    } else if (e.nodeOp == QueryNodeOp.Or) {
        return <QBOrBlock>{children}</QBOrBlock>
    }

    throw "Unsupported node element";
}