/**
 * Component for picking time
 *
 * @author Fedorov Platon
 * @date 2021-06-25
 */

import * as React from 'react';
import {safeInvoke} from '../..';
import {InputMask} from '../input/InputMask';
import {Props} from '../input/Input.types';

interface IState {
    hasError: boolean;
    errorMessage: string;
    time: string;
}

type IProps = Omit<Props, 'errorMessage'> & {
    errorMessage: string;
    onValidTimeChange?: (value: string) => void;
}

export class TimePicker extends React.Component<IProps, IState> {
    override state: IState = {
        hasError: false,
        errorMessage: '',
        time: this.props.value ? this.props.value.toString() : ''
    };

    input = React.createRef<HTMLInputElement>();

    onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.currentTarget.value;

        if (value !== '__:__:__' && !/^(([01][0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]$/.test(value)) {
            this.setState({hasError: true, errorMessage: this.props.errorMessage, time: value});
        } else {
            this.setState({hasError: false, errorMessage: '', time: value});

            if (value !== this.props.value) {
                safeInvoke(this.props.onValidTimeChange, value);
            }
        }

        safeInvoke(this.props.onChange, e);
    };

    override render () {
        const {onChange, hasError, onValidTimeChange, value, ...props} = this.props;
        const hasErrorFinal = hasError !== undefined ? hasError : this.state.hasError;
        const errorMessageFinal = this.state.errorMessage;

        let time = value ? value : '';

        if (document.activeElement === this.input.current) {
            time = this.state.time;
        }

        return (
            <InputMask
                value={time}
                mask={'99:99:99'}
                allowClear={true}
                onChange={this.onChange}
                hasError={hasErrorFinal}
                forwardRef={this.input}
                {...props}
                errorMessage={errorMessageFinal}
            />
        );
    }
}
