'use strict';

import _extends from "@babel/runtime/helpers/extends";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { FormControl } from './FormControl';
import { Icon } from '../Icon';
import { DateRange } from 'react-date-range';
import classnames from 'classnames';
import onClickOutside from 'react-onclickoutside';
import moment from 'moment';
import _ from 'lodash';
var ENTER_KEY_CODE = 13;
var SPACE_KEY_CODE = 32;
var ESC_KEY_CODE = 27;
export var DateRangePickerCtrl =
/*#__PURE__*/
function (_FormControl) {
  _inheritsLoose(DateRangePickerCtrl, _FormControl);

  function DateRangePickerCtrl(props, context) {
    var _this;

    _this = _FormControl.call(this, props, context) || this;

    _defineProperty(_assertThisInitialized(_this), "open", function () {
      _this.setState({
        open: true
      }, _this.addAccessibility);
    });

    _defineProperty(_assertThisInitialized(_this), "close", function () {
      if (_this.isDatePickerFocused()) {
        _this.refs.input.focus();
      }

      _this.removeAccessibility();

      _this.setState({
        open: false
      });
    });

    _defineProperty(_assertThisInitialized(_this), "closeUnfocused", function () {
      // Wait for changing a focus from input to popover and back
      setTimeout(function () {
        if (_this.stopClosing) {
          _this.stopClosing = false;
          return;
        }

        if (!_this.isInputFocused() && !_this.isDatePickerFocused()) {
          _this.close();
        }
      }, 50);
    });

    _defineProperty(_assertThisInitialized(_this), "toggle", function () {
      if (_this.state.open) {
        _this.close();
      } else {
        _this.open();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onDatePickerClick", function () {
      // Prevent close date picker by closeUnfocused method
      _this.stopClosing = true;
      setTimeout(function () {
        _this.stopClosing = false;
      }, 100);
    });

    _defineProperty(_assertThisInitialized(_this), "addAccessibility", function () {
      var node = ReactDOM.findDOMNode(_this.refs.dateRange);

      if (!node) {
        return;
      }

      var _this$props = _this.props,
          setPrevMonthText = _this$props.setPrevMonthText,
          setNextMonthText = _this$props.setNextMonthText;
      node.addEventListener('mousedown', _this.onDatePickerClick);
      node.addEventListener('keyup', _this.handleKeyboard);
      node.addEventListener('keydown', _this.closeUnfocused);

      _.toArray(node.querySelectorAll('.rdr-MonthAndYear-innerWrapper > span, .rdr-WeekDays')).forEach(function (item) {
        return item.setAttribute('role', 'presentation');
      });

      _.toArray(node.querySelectorAll('.rdr-PredefinedRangesItem')).forEach(function (item) {
        item.setAttribute('aria-label', item.innerText);
        item.setAttribute('role', 'button');
        item.addEventListener('keydown', function (e) {
          if (e.keyCode === ENTER_KEY_CODE || e.keyCode === SPACE_KEY_CODE) {
            setTimeout(_this.close, 100);
          }
        });
      });

      _.toArray(node.querySelectorAll('.rdr-MonthAndYear-button.prev')).forEach(function (item) {
        item.setAttribute('aria-label', setPrevMonthText);
        item.addEventListener('click', _this.addDaysAccessibilityAfterChangeMonth);
      });

      _.toArray(node.querySelectorAll('.rdr-MonthAndYear-button.next')).forEach(function (item) {
        item.setAttribute('aria-label', setNextMonthText);
        item.addEventListener('click', _this.addDaysAccessibilityAfterChangeMonth);
      });

      _.toArray(node.querySelectorAll('[tabindex="0"]')).forEach(function (item) {
        item.addEventListener('blur', _this.closeUnfocused);
      });

      _this.addDaysAccessibility();
    });

    _defineProperty(_assertThisInitialized(_this), "removeAccessibility", function () {
      var node = ReactDOM.findDOMNode(_this.refs.dateRange);

      if (!node) {
        return;
      }

      node.removeEventListener('mousedown', _this.onDatePickerClick);
      node.removeEventListener('keyup', _this.handleKeyboard);

      _.toArray(node.querySelectorAll('.rdr-MonthAndYear-button.prev')).forEach(function (item) {
        item.removeEventListener('click', _this.addDaysAccessibilityAfterChangeMonth);
      });

      _.toArray(node.querySelectorAll('.rdr-MonthAndYear-button.next')).forEach(function (item) {
        item.removeEventListener('click', _this.addDaysAccessibilityAfterChangeMonth);
      });

      _.toArray(node.querySelectorAll('[tabindex="0"]')).forEach(function (item) {
        item.removeEventListener('blur', _this.closeUnfocused);
      });
    });

    _defineProperty(_assertThisInitialized(_this), "addDaysAccessibility", function () {
      var node = ReactDOM.findDOMNode(_this.refs.dateRange);

      if (!node) {
        return;
      }

      _.toArray(node.querySelectorAll('.rdr-Day.is-passive')).forEach(function (item) {
        item.removeAttribute('tabindex');
        item.removeAttribute('aria-label');
        item.setAttribute('role', 'presentation');
      });

      _.toArray(node.querySelectorAll('.rdr-Day[aria-selected]:not(.is-selected)')).forEach(function (item) {
        item.removeAttribute('aria-selected');
      });

      _.toArray(node.querySelectorAll('.rdr-Day:not(.is-passive)')).forEach(function (item) {
        item.setAttribute('tabindex', '0');
        item.setAttribute('aria-label', item.innerText);
        item.setAttribute('role', 'button');
      });

      _.toArray(node.querySelectorAll('.rdr-Day.is-selected')).forEach(function (item) {
        item.setAttribute('aria-selected', 'true');
      });
    });

    _defineProperty(_assertThisInitialized(_this), "addDaysAccessibilityAfterChangeMonth", function () {
      setTimeout(_this.addDaysAccessibility, 200);
    });

    _defineProperty(_assertThisInitialized(_this), "handleKeyboard", function (event) {
      switch (event.keyCode) {
        case ENTER_KEY_CODE:
        case SPACE_KEY_CODE:
          event.target.click();
          break;

        case ESC_KEY_CODE:
          _this.close();

          break;
      }
    });

    _defineProperty(_assertThisInitialized(_this), "handleChange", function (which, payload) {
      if (_this.props.onChange) {
        _this.props.onChange(payload);
      }

      _this.close();
    });

    _defineProperty(_assertThisInitialized(_this), "handleClickOutside", function () {
      _this.close();
    });

    _this.state = {
      open: false
    };
    return _this;
  }

  var _proto = DateRangePickerCtrl.prototype;

  _proto.getFieldValue = function getFieldValue(value) {
    if (!value) {
      return moment();
    }

    if (typeof value === 'number') {
      return moment(value);
    }

    if (typeof value === 'string' && moment(value).isValid()) {
      return moment(value);
    }

    if (value instanceof Date) {
      return moment(value);
    }

    return value;
  };

  _proto.isInputFocused = function isInputFocused() {
    return document.activeElement === ReactDOM.findDOMNode(this.refs.input);
  };

  _proto.isDatePickerFocused = function isDatePickerFocused() {
    if (!this.state.open) {
      return false;
    }

    var node = ReactDOM.findDOMNode(this.refs.dateRange);
    return !!(node && node.querySelector(':focus'));
  };

  _proto.render = function render() {
    var props = this.getPropsFromContext();
    var disabled = false;
    moment.locale(props.locale);
    var startDate = this.getFieldValue(props.startDate);
    var endDate = this.getFieldValue(props.endDate);
    return React.createElement("div", {
      className: classnames('rc-daterangepicker', {
        'rc-datepicker-disabled': disabled
      })
    }, React.createElement(Icon, {
      name: "calendar",
      onClick: this.toggle
    }), React.createElement("div", {
      className: "rdt"
    }, React.createElement("input", {
      className: "form-control",
      onFocus: this.open,
      onBlur: this.closeUnfocused,
      onClick: this.open,
      onKeyDown: this.handleKeyboard,
      id: props.id,
      key: "i",
      type: "text",
      ref: "input",
      readOnly: true,
      value: this.props.valueFormatter(startDate, endDate),
      "aria-label": this.props.ariaLabel
    }), this.renderDateRange()));
  };

  _proto.renderDateRange = function renderDateRange() {
    if (this.state.open) {
      var props = this.getPropsFromContext();
      var startDate = this.getFieldValue(props.startDate);
      var endDate = this.getFieldValue(props.endDate);
      return React.createElement(DateRangeCmp, _extends({}, props, {
        startDate: startDate,
        endDate: endDate,
        handleChange: this.handleChange,
        ref: "dateRange"
      }));
    }

    return null;
  };

  return DateRangePickerCtrl;
}(FormControl);

_defineProperty(DateRangePickerCtrl, "propTypes", Object.assign({}, FormControl.propTypes, {
  ranges: PropTypes.object,
  onChange: PropTypes.func,
  startDate: PropTypes.any,
  endDate: PropTypes.any,
  locale: PropTypes.string,
  valueFormatter: PropTypes.func,
  ariaLabel: PropTypes.string,
  setPrevMonthText: PropTypes.string,
  setNextMonthText: PropTypes.string
}));

_defineProperty(DateRangePickerCtrl, "defaultProps", Object.assign({}, FormControl.defaultProps, {
  locale: 'en_US',
  value: null,
  valueFormatter: defaultValueFormatter,
  ariaLabel: 'TRANSLATE:CHOOSE_DATE_RANGE',
  setPrevMonthText: 'TRANSLATE:SET_PREV_MONTH',
  setNextMonthText: 'TRANSLATE:SET_NEXT_MONTH'
}));

var DateRangeCmp =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(DateRangeCmp, _React$Component);

  function DateRangeCmp() {
    return _React$Component.apply(this, arguments) || this;
  }

  var _proto2 = DateRangeCmp.prototype;

  _proto2.render = function render() {
    return React.createElement(DateRange, _extends({}, this.props, {
      classNames: {
        dateRange: 'rdtPicker dropdown-menu'
      },
      onlyClasses: true,
      linkedCalendars: true,
      twoStepChange: true,
      onChange: this.props.handleChange.bind(this, 'predefined')
    }));
  };

  return DateRangeCmp;
}(React.Component);

_defineProperty(DateRangeCmp, "propTypes", {
  handleChange: PropTypes.func.isRequired
});

export var DateRangePickerControl = onClickOutside(DateRangePickerCtrl);

function defaultValueFormatter(startDate, endDate) {
  if (startDate.isSame(endDate, 'date')) {
    return startDate.format('L');
  }

  return startDate.format('L') + ' - ' + endDate.format('L');
}