import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import IDUtil from '../../../util/IDUtil';
import TimeInput from './TimeInput';

export default class SelectionTemporalForm extends React.PureComponent {
    constructor(props) {
        super(props);
        this.start = React.createRef();
        this.end = React.createRef();
    }

    onAdd = () => {
        let start = this.start.current.getValue();
        let end = this.end.current.getValue();

        // prevent start > end
        if (start > end) {
            const tmp = end;
            end = start;
            start = tmp;

            this.start.current.setValue(start);
            this.end.current.setValue(end);
        }

        const selection = Object.assign({}, this.props.selection, {
            start,
            end
        });
        this.props.onUpdate(selection);
    };

    render() {
        return (
            <div
                className={classNames(
                    IDUtil.cssClassName('selection-temporal-form')
                )}
            >
                <label>Start</label>
                <TimeInput
                    ref={this.start}
                    time={this.props.selection.start}
                    onFinish={this.onAdd}
                />
                <label>End</label>
                <TimeInput
                    ref={this.end}
                    time={this.props.selection.end}
                    onFinish={this.onAdd}
                />
                <button className="btn btn-primary" onClick={this.onAdd}>
                    Add
                </button>
            </div>
        );
    }
}

SelectionTemporalForm.propTypes = {
    selection: PropTypes.object.isRequired,
    onUpdate: PropTypes.func.isRequired
};
