/**
 * Component for render field with number input
 *
 * @author: Brauer Ilya
 * @date: 2022-07-11
 */

import * as React from 'react';
import {Field, IFieldProps} from './Field';
import * as styles from './field.m.css';
import {Input} from '../..';
import {IInputNumber} from '../../component/input/InputNumber';
import {filterProps} from '../../utils/filterProps';

export type IFieldNumberProps = IFieldProps & Omit<IInputNumber, 'onChange' | 'isDisabled'> & {
    disabled?: boolean;
    name?: string;
    onChange: (name: string, value: number) => void;
    onEnter?: () => void;
    items?: IFieldNumberProps[];
};

const defaultProps = {
    disabled: false,
    readOnly: false
};

export class FieldNumber extends React.PureComponent<IFieldNumberProps> {

    static defaultProps = defaultProps;

    get inputChildren () {

        if (this.props.items) {
            return (
                <div className={styles.itemsContainer}>

                    {this.props.items.map((item) => {
                        return (
                            <div key={item.name} style={{width: `${item.inputWidth}%`}} className={styles.fieldInputContainer}>
                                <Input.Number {...this.inputProps(item)} errorMessage={item.error}/>
                            </div>
                        );
                    })}
                </div>
            );
        }

        return (
            <Input.Number {...this.inputProps(this.props)} />
        );
    }

    inputProps = (inputParams: IFieldNumberProps) => {
        const value = inputParams.defaultValue;

        let props: IInputNumber = {
            ...filterProps<IFieldNumberProps, IInputNumber>(inputParams, ['isRequired', 'defaultValue']),
            value: value,
            isDisabled: inputParams.disabled,
            onChange: this.onChange,
            onKeyDown: (inputParams.onEnter !== undefined) ? this.onKeyDown : undefined
        };

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

        return props;
    }

    onChange = (value: number) => {
        this.props.onChange(this.props.name || '', value);
    }

    onKeyDown = (e: any) => {
        if (e.key === 'Enter' && this.props.onEnter) {
            this.props.onEnter();
        }
    }

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