import React from 'react';
import IDUtil from '../../util/IDUtil';
import TimeUtil from '../../util/TimeUtil';
import ElasticsearchDataUtil from '../../util/ElasticsearchDataUtil';
import DatePickerSelector from './DatePickerSelector';
import moment from 'moment-timezone';


class DateRangeSelector extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            slider: null
        };
        this.CLASS_PREFIX = 'drs';
    }

    //only update on a new search
    shouldComponentUpdate(nextProps, nextState) {
        return nextProps.searchId != this.props.searchId;
    }

    //the data looks like this => {start : '' : end : '', dateField : ''}
    onOutput(data) {
        if (this.props.onOutput) {
            this.props.onOutput(this.constructor.name, data);
        }
    }

    //will propagate the selected dates to the QueryBuilder
    onComponentOutput(componentClass, data) {
        if(componentClass == 'DatePickerSelector') {
            const df = this.props.dateRange.field;
            if (this.props.aggregations && data) {
                if (this.props.aggregations[df]) {
                    this.onOutput({
                        field: this.props.dateRange.field,
                        start: data.start ? data.start.valueOf() : null,
                        end: data.end ? data.end.valueOf() : null
                    });
                }
            }
        }
    }

    // Date picker should always show the other dates as well, not be related to the resultset
    getMinDateDatePicker() {
        const minYear = this.props.collectionConfig.getMinimumYear();
        const minDate = new Date(Date.parse(minYear+"-01-01"));

        return minDate;
    }

    getMaxDateDatePicker() {
        const maxYear = this.props.collectionConfig.getMaximumYear();
        const today = moment();

        if (maxYear == -1) {
            //just return today
            return today.toDate();
        }
        const maxDate = new Date(Date.parse(maxYear+"-12-31"));

        return maxDate;
    }

  render() {
        return (
            <div id={'__dps__' + IDUtil.hashCode(this.props.queryId)} className="datePickerSelector">
                <div className={IDUtil.cssClassName('date-range-select', this.CLASS_PREFIX)}>
                    <div>
                        {this.props.dateRange !== null && (
                        <DatePickerSelector
                            disabled={this.props.dateRange == null}
                            minDate={this.getMinDateDatePicker()}
                            maxDate={this.getMaxDateDatePicker()}
                            dateRange={this.props.dateRange}
                            onOutput={this.onComponentOutput.bind(this)}
                        />)}
                    </div>
                </div>
            </div>
        )
    }
}

export default DateRangeSelector;
