'use strict';

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.DateRangePickerControl = exports.DateRangePickerCtrl = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireDefault(require("react"));

var _reactDom = _interopRequireDefault(require("react-dom"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _FormControl2 = require("./FormControl");

var _Icon = require("../Icon");

var _reactDateRange = require("react-date-range");

var _classnames = _interopRequireDefault(require("classnames"));

var _reactOnclickoutside = _interopRequireDefault(require("react-onclickoutside"));

var _moment = _interopRequireDefault(require("moment"));

var _lodash = _interopRequireDefault(require("lodash"));

var ENTER_KEY_CODE = 13;
var SPACE_KEY_CODE = 32;
var ESC_KEY_CODE = 27;

var DateRangePickerCtrl =
/*#__PURE__*/
function (_FormControl) {
  (0, _inheritsLoose2.default)(DateRangePickerCtrl, _FormControl);

  function DateRangePickerCtrl(props, context) {
    var _this;

    _this = _FormControl.call(this, props, context) || this;
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "open", function () {
      _this.setState({
        open: true
      }, _this.addAccessibility);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "close", function () {
      if (_this.isDatePickerFocused()) {
        _this.refs.input.focus();
      }

      _this.removeAccessibility();

      _this.setState({
        open: false
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_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);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "toggle", function () {
      if (_this.state.open) {
        _this.close();
      } else {
        _this.open();
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onDatePickerClick", function () {
      // Prevent close date picker by closeUnfocused method
      _this.stopClosing = true;
      setTimeout(function () {
        _this.stopClosing = false;
      }, 100);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "addAccessibility", function () {
      var node = _reactDom.default.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);

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

      _lodash.default.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);
          }
        });
      });

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

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

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

      _this.addDaysAccessibility();
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "removeAccessibility", function () {
      var node = _reactDom.default.findDOMNode(_this.refs.dateRange);

      if (!node) {
        return;
      }

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

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

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

      _lodash.default.toArray(node.querySelectorAll('[tabindex="0"]')).forEach(function (item) {
        item.removeEventListener('blur', _this.closeUnfocused);
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "addDaysAccessibility", function () {
      var node = _reactDom.default.findDOMNode(_this.refs.dateRange);

      if (!node) {
        return;
      }

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

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

      _lodash.default.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');
      });

      _lodash.default.toArray(node.querySelectorAll('.rdr-Day.is-selected')).forEach(function (item) {
        item.setAttribute('aria-selected', 'true');
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "addDaysAccessibilityAfterChangeMonth", function () {
      setTimeout(_this.addDaysAccessibility, 200);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_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;
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleChange", function (which, payload) {
      if (_this.props.onChange) {
        _this.props.onChange(payload);
      }

      _this.close();
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleClickOutside", function () {
      _this.close();
    });
    _this.state = {
      open: false
    };
    return _this;
  }

  var _proto = DateRangePickerCtrl.prototype;

  _proto.getFieldValue = function getFieldValue(value) {
    if (!value) {
      return (0, _moment.default)();
    }

    if (typeof value === 'number') {
      return (0, _moment.default)(value);
    }

    if (typeof value === 'string' && (0, _moment.default)(value).isValid()) {
      return (0, _moment.default)(value);
    }

    if (value instanceof Date) {
      return (0, _moment.default)(value);
    }

    return value;
  };

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

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

    var node = _reactDom.default.findDOMNode(this.refs.dateRange);

    return !!(node && node.querySelector(':focus'));
  };

  _proto.render = function render() {
    var props = this.getPropsFromContext();
    var disabled = false;

    _moment.default.locale(props.locale);

    var startDate = this.getFieldValue(props.startDate);
    var endDate = this.getFieldValue(props.endDate);
    return _react.default.createElement("div", {
      className: (0, _classnames.default)('rc-daterangepicker', {
        'rc-datepicker-disabled': disabled
      })
    }, _react.default.createElement(_Icon.Icon, {
      name: "calendar",
      onClick: this.toggle
    }), _react.default.createElement("div", {
      className: "rdt"
    }, _react.default.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.default.createElement(DateRangeCmp, (0, _extends2.default)({}, props, {
        startDate: startDate,
        endDate: endDate,
        handleChange: this.handleChange,
        ref: "dateRange"
      }));
    }

    return null;
  };

  return DateRangePickerCtrl;
}(_FormControl2.FormControl);

exports.DateRangePickerCtrl = DateRangePickerCtrl;
(0, _defineProperty2.default)(DateRangePickerCtrl, "propTypes", Object.assign({}, _FormControl2.FormControl.propTypes, {
  ranges: _propTypes.default.object,
  onChange: _propTypes.default.func,
  startDate: _propTypes.default.any,
  endDate: _propTypes.default.any,
  locale: _propTypes.default.string,
  valueFormatter: _propTypes.default.func,
  ariaLabel: _propTypes.default.string,
  setPrevMonthText: _propTypes.default.string,
  setNextMonthText: _propTypes.default.string
}));
(0, _defineProperty2.default)(DateRangePickerCtrl, "defaultProps", Object.assign({}, _FormControl2.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) {
  (0, _inheritsLoose2.default)(DateRangeCmp, _React$Component);

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

  var _proto2 = DateRangeCmp.prototype;

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

  return DateRangeCmp;
}(_react.default.Component);

(0, _defineProperty2.default)(DateRangeCmp, "propTypes", {
  handleChange: _propTypes.default.func.isRequired
});
var DateRangePickerControl = (0, _reactOnclickoutside.default)(DateRangePickerCtrl);
exports.DateRangePickerControl = DateRangePickerControl;

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

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