/**
 * empty comment line Ivan Marshalkin
 *
 * @author: Ivan Marshalkin
 * @date: 2019-04-19
 */

import * as React from 'react';
import {TreeSelect} from 'antd';
import {Icon} from '../../component/icon/Icon';
import {Field, IFieldProps} from './Field';


export type TreeNodeType = {
    key: number;
    value: string;
    title: string;
    icon: 'book' | 'profile';
    selectable: boolean;
    leaf: boolean;
    disabled?: boolean;
    children?: TreeNodeType[];
};


type IFieldTreeSelectProps = IFieldProps & {
    name?: string;
    options: TreeNodeType[];
    value?: string | number | boolean | null;
    defaultValue?: string | number | boolean | null;
    onSelect: (name: string) => void;
    onChange?: (name: string) => void;
    disabled?: boolean;
    error?: string;
    placeholder?: string;
    allowClear?: boolean;
}

const defaultProps = {
    disabled: false as boolean,
    allowClear: false as boolean
};

export class FieldTreeSelect extends React.PureComponent<IFieldTreeSelectProps> {

    static defaultProps = defaultProps;

    get inputProps () {
        let props: any = {
            name: this.props.name,
            value: this.props.value,
            onSelect: this.props.onSelect,
            onChange: this.props.onChange,
            style: {width: '100%'},
            children: this.treeNodes(this.props.options),
            placeholder: this.props.placeholder,
            allowClear: this.props.allowClear
        };

        const inputErrorCls = 'ud-field-input_error';

        if (this.props.disabled) {
            props.disabled = true;
        }

        if (this.props.error) {
            props['className'] = props['className'] ? props['className'] + ' ' + inputErrorCls : inputErrorCls;
        }

        return props;
    }

    treeNodes = (options: TreeNodeType[] = []) => {
        let result = [];

        options = options.filter((item) => {
            return item.leaf === false ? (item.children && item.children.length > 0) : true;
        });

        for (let n = 0; n < options.length; ++n) {
            result.push(this.treeNodeComponent(options[n]));
        }

        return result;
    }

    treeNodeComponent = ({key, value, title, icon, children, disabled, selectable, leaf}: TreeNodeType) => {
        const nodeTitle = () => {
            if (!icon) {
                return title;
            }

            return (
                <span><Icon name={icon} /> {title}</span>
            );
        };

        return (
            <TreeSelect.TreeNode {...{key, value, selectable, leaf, disabled, title: nodeTitle()}}>
                {this.treeNodes(children)}
            </TreeSelect.TreeNode>
        );
    }

    override render () {
        return (
            <Field
                {...this.props}
            >
                <TreeSelect {...this.inputProps} />
            </Field>
        );
    }
}
