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

type InputTimeProps = Omit<Props, 'errorMessage'> & {
    errorMessage: string;
}

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

export class InputTime extends React.Component<InputTimeProps, IState> {
    override state: IState = {
        hasError: false,
        errorMessage: ''
    };

    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});
        } else {
            this.setState({hasError: false, errorMessage: ''});
        }

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

    override render () {
        const {onChange, ...props} = this.props;
        const hasError = this.state.hasError || this.props.hasError;
        const allowClear = props.allowClear === undefined ? true : props.allowClear;

        return (
            <InputMask
                mask={'99:99:99'}
                allowClear={allowClear}
                onChange={this.onChange}
                hasError={hasError}
                {...props}
            />
        );
    }
}
