import React from 'react';
import { Box } from '@material-ui/core';
import QBQueryButton from './QBEditButton';
import { QBQueryElem } from './QBQueryElem';
import { QueryElem, addPlaceholders, removePlaceholders, simplify } from '../../lib/query/Query';

export interface TagItem {
    name: string,
    id: number,
    childIds: number[],
    parentId?: number,
}

export interface Requests {
    getArtists: (filter: string) => Promise<string[]>,
    getAlbums: (filter: string) => Promise<string[]>,
    getSongTitles: (filter: string) => Promise<string[]>,
    getTags: () => Promise<TagItem[]>,
}

export interface IProps {
    query: QueryElem | null,
    editing: boolean,
    onChangeEditing: (e: boolean) => void,
    onChangeQuery: (q: QueryElem | null) => void,
    requestFunctions: Requests,
}

export default function QueryBuilder(props: IProps) {
    const simpleQuery = simplify(props.query);
    const showQuery = props.editing ?
        addPlaceholders(simpleQuery, null) : simpleQuery;

    const onReplace = (q: any) => {
        const newQ = removePlaceholders(q);
        props.onChangeEditing(false);
        props.onChangeQuery(newQ);
    }

    return <>
        <Box display="flex" alignItems="center">
            <Box m={2}>
                <QBQueryButton
                    onClick={() => props.onChangeEditing(!props.editing)}
                    editing={props.editing}
                />
            </Box>
            <Box m={2}>
                {showQuery && <QBQueryElem
                    elem={showQuery}
                    onReplace={onReplace}
                    editingQuery={props.editing}
                    requestFunctions={props.requestFunctions}
                />}
            </Box>
        </Box>
    </>
}