import React, { Component } from 'react';
import PropTypes from 'prop-types';
import DatepickerRange from '../atoms/DatepickerRange';
import newId from '../utils/newId';

export default class FilterDatepickerRangeField extends Component {
  constructor(props) {
    super(props);
    this.onDatesChange = this.onDatesChange.bind(this);
  }

  componentWillMount() {
    // We need some way to identify ourselves to the Toolbar.Filter component keeping track of active filters.
    this.startDateId = newId();
    this.endDateId = newId();

    this.updateActiveState();
  }

  componentWillUnmount() {
    if (this.context.setFilterActive) {
      this.context.setFilterActive(this.startDateId, false);
      this.context.setFilterActive(this.endDateId, false);
    }
  }

  onDatesChange(dates) {
    this.updateActiveState();
    if (this.props.onDatesChange) this.props.onDatesChange(dates);
  }

  updateActiveState() {
    this.context.setFilterActive(this.startDateId, this.props.startDate !== null);
    this.context.setFilterActive(this.endDateId, this.props.endDate !== null);
  }

  render() {
    return (
      <DatepickerRange
        {...this.props}
        onDatesChange={this.onDatesChange}
      />
    );
  }
}

FilterDatepickerRangeField.contextTypes = {
  setFilterActive: PropTypes.func
};
