import React from 'react';
import PropTypes from 'prop-types';
import {MultiSelect, MultiSelectDefaultProps, MultiSelectProps} from './MultiSelect';
import {FormControl} from './FormControl';

type TreeFilterControlProps = {
    maxDepth?: number;
    tree: object;
} & MultiSelectProps &
    Partial<TreeFilterControlDefaultProps>;

type TreeFilterControlDefaultProps = {
    block: boolean;
    testAutomationId: string;
} & MultiSelectDefaultProps;

export class TreeFilterControl extends FormControl<TreeFilterControlProps> {
    static propTypes: any = {
        ...MultiSelect.propTypes,
        maxDepth: PropTypes.number,
        tree: PropTypes.object.isRequired
    };

    static defaultProps = {
        ...MultiSelect.defaultProps,
        block: true,
        testAutomationId: 'treeFilter',
        maxDepth: null
    };

    // not implemented actually. used to suppress TS error
    getValue(): any {}

    renderTree(treeNode, depth, maxDepth) {
        const {id, label, items} = treeNode;
        if (items && items.length > 0 && (maxDepth === null || depth < maxDepth)) {
            let nestedNodes = items.map(childNode => {
                return this.renderTree(childNode, depth + 1, maxDepth);
            });

            return (
                <MultiSelect.Group key={id}>
                    <MultiSelect.MasterOption value={id} label={label} />
                    {nestedNodes}
                </MultiSelect.Group>
            );
        }
        return <MultiSelect.Option key={id} value={id} label={label} />;
    }

    render() {
        const {tree, maxDepth, ...props} = this.props;
        let options = this.renderTree(tree, 1, maxDepth);
        return <MultiSelect {...props}>{options}</MultiSelect>;
    }
}
