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

import * as React from 'react';
import {Field, IFieldProps} from './Field';
import {ISelectProps, Select, Value as SelectValue, safeInvoke} from '../..';

export type IFieldSelectProps = IFieldProps & Omit<ISelectProps, 'onChange' | 'onSelect' | 'onDeselect' | 'onSearch'> & {
    name: string;
    onSelect?: (name: string, value: SelectValue) => void;
    onDeselect?: (name: string, value: string) => void;
    onSearch?: (name: string, value: any) => void;
    onChange?: (name: string, value: SelectValue) => void;
    overlapButton?: JSX.Element;
}

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

export class FieldSelect extends React.Component<IFieldSelectProps> {

    static defaultProps = defaultProps;

    get inputProps () {
        let props: ISelectProps = {
            ...this.props,
            onSelect: this.handleOnSelect,
            onSearch: this.handleOnSearch,
            onDeselect: this.handleOnDeselect,
            onChange: this.handleOnChange,
            mode: this.props.mode === undefined ? 'default' : this.props.mode
        };

        if (this.props.error) {
            props.hasError = true;
        }

        return props;
    }

    handleOnSelect = (value: SelectValue) => {
        safeInvoke(this.props.onSelect, this.props.name, value);
    };

    handleOnSearch = (value: string | number | boolean) => {
        safeInvoke(this.props.onSearch, this.props.name, value);
    };

    handleOnDeselect = (value: string) => {
        safeInvoke(this.props.onDeselect, this.props.name, value);
    };

    handleOnChange = (value: SelectValue) => {
        safeInvoke(this.props.onChange, this.props.name, value);
    };

    override render () {
        const {overlapButton} = this.props;

        return (
            <Field
                {...this.props}
            >
                {overlapButton ? (
                    <div>
                        <Select {...this.inputProps}/>
                        {overlapButton}
                    </div>
                  ) : <Select {...this.inputProps}/>
                }
            </Field>
        );
    }
}
