import React from 'react';
import QBOrBlock from './QBOrBlock';
import QBAndBlock from './QBAndBlock';
import { QueryNodeElem, QueryNodeOp, QueryElem, simplify, QueryLeafElem, isLeafElem } from '../../lib/query/Query';
import { QBQueryElem } from './QBQueryElem';
import { Requests } from './QueryBuilder';
import { Modifier, QBLeafElem } from './QBLeafElem';

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

export function QBNodeElem(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 newq = { operands: ops, nodeOp: e.nodeOp };
        let newNode = simplify(newq, null);
        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}
            requestFunctions={props.requestFunctions}
        />
    });

    if (e.nodeOp === QueryNodeOp.And) {
        return <QBAndBlock>{children}</QBAndBlock>
    } else if (e.nodeOp === QueryNodeOp.Or) {
        return <QBOrBlock>{children}</QBOrBlock>
    } else if (e.nodeOp === QueryNodeOp.Not &&
               isLeafElem(e.operands[0])) {
        return <QBLeafElem
            elem={e.operands[0] as QueryLeafElem}
            onReplace={props.onReplace}
            editingQuery={props.editingQuery}
            requestFunctions={props.requestFunctions}
            modifier={Modifier.Not}
        />
    }

    console.log("Unsupported node element:", e);
    throw new Error("Unsupported node element");
}