"use strict";

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

exports.__esModule = true;
exports.BSDatePicker = void 0;

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 _reactDatetime = _interopRequireDefault(require("react-datetime"));

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

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

var ENTER_KEY_CODE = 13;
var SPACE_KEY_CODE = 32;
var ESC_KEY_CODE = 27;
var VIEWS = {
  DAYS: 'days',
  MONTHS: 'months',
  YEARS: 'years',
  TIME: 'time'
};
var blurSelector = '[tabindex="0"], .rdt > input';
/**
 * @param {string} eventName
 * @param {{[bubbles]: Boolean, [cancelable]: Boolean}} eventArgs
 * */

var createMouseEvent = function createMouseEvent(eventName, eventArgs) {
  if (eventArgs === void 0) {
    eventArgs = {};
  }

  try {
    return new MouseEvent(eventName, eventArgs);
  } catch (e) {
    // https://jira.ringcentral.com/browse/UIA-68403
    var event = document.createEvent('MouseEvent');
    event.initMouseEvent(eventName, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    return event;
  }
};

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

  function BSDatePicker() {
    var _this;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _BSDateTimeControl.call.apply(_BSDateTimeControl, [this].concat(args)) || this;
    (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), "closeUnfocused", function () {
      // Wait for changing a focus from input to popover and back
      setTimeout(function () {
        if (_this.stopClosing) {
          _this.stopClosing = false;
          return;
        }

        if (!_this.isFocused()) {
          _this.closeCalendar();
        }
      }, 50);
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "focusInput", function () {
      var node = _reactDom.default.findDOMNode((0, _assertThisInitialized2.default)(_this));

      var input = node.querySelector('.rdt > input.form-control');

      if (input) {
        input.focus();
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "mouseDownByKeyboard", function (event) {
      _this.closeUnfocused();

      if (event.keyCode === ESC_KEY_CODE) {
        event.stopPropagation();

        _this.focusInput();

        _this.closeCalendar();
      }

      if (_this.props.disabled || event.target.isMouseDownByKeyboard) {
        return;
      }

      if (event.keyCode === ENTER_KEY_CODE || event.keyCode === SPACE_KEY_CODE) {
        event.target.dispatchEvent(createMouseEvent('mousedown', {
          bubbles: true
        }));
        event.target.isMouseDownByKeyboard = true;
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "mouseUpByKeyboard", function (event) {
      if (_this.props.disabled) {
        return;
      }

      if (event.keyCode === ESC_KEY_CODE) {
        event.stopPropagation();
      }

      if (event.keyCode === ENTER_KEY_CODE || event.keyCode === SPACE_KEY_CODE) {
        event.target.isMouseDownByKeyboard = false;
        event.target.dispatchEvent(createMouseEvent('mouseup', {
          bubbles: true
        }));
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "clickByKeyboard", function (event) {
      if (_this.props.disabled) {
        return;
      }

      if (event.keyCode === ENTER_KEY_CODE || event.keyCode === SPACE_KEY_CODE) {
        event.target.click();
      }
    });
    return _this;
  }

  var _proto = BSDatePicker.prototype;

  _proto.componentDidMount = function componentDidMount() {
    this.adjustForRC();
    this.addEventListeners();
  };

  _proto.componentDidUpdate = function componentDidUpdate() {
    this.adjustForRC();
  };

  _proto.componentWillUnmount = function componentWillUnmount() {
    this.removeEventListeners();
  };

  _proto.adjustForRC = function adjustForRC() {
    var _this2 = this;

    var _this$props = this.props,
        disabled = _this$props.disabled,
        changeYearText = _this$props.changeYearText,
        changeMonthText = _this$props.changeMonthText,
        setPrevDecadeText = _this$props.setPrevDecadeText,
        setNextDecadeText = _this$props.setNextDecadeText,
        setPrevYearText = _this$props.setPrevYearText,
        setNextYearText = _this$props.setNextYearText,
        setPrevMonthText = _this$props.setPrevMonthText,
        setNextMonthText = _this$props.setNextMonthText,
        setPrevHourText = _this$props.setPrevHourText,
        setNextHourText = _this$props.setNextHourText,
        setPrevMinuteText = _this$props.setPrevMinuteText,
        setNextMinuteText = _this$props.setNextMinuteText,
        toggleAMPMText = _this$props.toggleAMPMText;
    var currentView = this.state.currentView;

    var setAutomationId = function setAutomationId(node, testId) {
      if (node) {
        node.setAttribute('data-test-automation-id', testId);
      }
    };

    var setKeyboardInteractive = function setKeyboardInteractive(node, interactive) {
      if (interactive === void 0) {
        interactive = true;
      }

      if (node) {
        if (interactive && !disabled) {
          node.setAttribute('role', 'button');
          node.setAttribute('tabindex', 0);
          node.addEventListener('keydown', _this2.mouseDownByKeyboard);
        } else {
          node.removeAttribute('role');
          node.removeAttribute('tabindex');
        }
      }
    };

    var setAriaLabel = function setAriaLabel(node, ariaLabel) {
      if (node) {
        if (ariaLabel) {
          node.setAttribute('aria-label', ariaLabel);
        } else {
          node.removeAttribute('aria-label');
        }
      }
    };

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

    var previousButton = node.querySelector('.rdtPrev');
    var nextButton = node.querySelector('.rdtNext');
    var switchViewButton = node.querySelector('.rdtSwitch');
    var switchToTimeViewButton = node.querySelector('.rdtTimeToggle');

    var _$toArray = _lodash.default.toArray(node.querySelectorAll(".rdtCounters .rdtBtn")),
        hoursUp = _$toArray[0],
        hoursDown = _$toArray[1],
        minutesUp = _$toArray[2],
        minutesDown = _$toArray[3],
        AMPMUp = _$toArray[4],
        AMPMDown = _$toArray[5];

    var _$toArray2 = _lodash.default.toArray(node.querySelectorAll('.rdtCounters .rdtCount')),
        hour = _$toArray2[0],
        minute = _$toArray2[1],
        ampm = _$toArray2[2];

    setAutomationId(node.querySelector('.rdtPicker'), 'datePickerOverlay');
    setAutomationId(previousButton, 'buttonPrev');
    setAutomationId(nextButton, 'buttonNext');
    setAutomationId(switchViewButton, 'buttonSwitch');
    setAutomationId(switchToTimeViewButton, 'buttonSwitchTime');
    setAutomationId(hoursUp, 'buttonUpHour');
    setAutomationId(hoursDown, 'buttonDownHour');
    setAutomationId(minutesUp, 'buttonUpMinute');
    setAutomationId(minutesDown, 'buttonDownMinute');
    setAutomationId(AMPMUp, 'buttonUpPMAM');
    setAutomationId(AMPMDown, 'buttonDownPMAM');
    setAutomationId(hour, 'currentHour');
    setAutomationId(minute, 'currentMinute');
    setAutomationId(ampm, 'currentPMAM');
    setKeyboardInteractive(previousButton);
    setKeyboardInteractive(nextButton);
    setKeyboardInteractive(switchViewButton, currentView !== VIEWS.YEARS);
    setKeyboardInteractive(switchToTimeViewButton);
    setKeyboardInteractive(hoursUp);
    setKeyboardInteractive(hoursDown);
    setKeyboardInteractive(minutesUp);
    setKeyboardInteractive(minutesDown);
    setKeyboardInteractive(AMPMUp);
    setKeyboardInteractive(AMPMDown);

    switch (currentView) {
      case VIEWS.DAYS:
        if (switchViewButton) {
          setAriaLabel(switchViewButton, switchViewButton.innerText + ", " + changeMonthText);
        }

        setAriaLabel(previousButton, setPrevMonthText);
        setAriaLabel(nextButton, setNextMonthText);
        break;

      case VIEWS.MONTHS:
        if (switchViewButton) {
          setAriaLabel(switchViewButton, switchViewButton.innerText + ", " + changeYearText);
        }

        setAriaLabel(previousButton, setPrevYearText);
        setAriaLabel(nextButton, setNextYearText);
        break;

      case VIEWS.YEARS:
        if (switchViewButton) {
          setAriaLabel(switchViewButton, switchViewButton.innerText);
        }

        setAriaLabel(previousButton, setPrevDecadeText);
        setAriaLabel(nextButton, setNextDecadeText);
        break;

      case VIEWS.TIME:
        setAriaLabel(hoursUp, setPrevHourText);
        setAriaLabel(hoursDown, setNextHourText);
        setAriaLabel(minutesUp, setPrevMinuteText);
        setAriaLabel(minutesDown, setNextMinuteText);
        setAriaLabel(AMPMUp, toggleAMPMText);
        setAriaLabel(AMPMDown, toggleAMPMText);
        break;
    }

    if (this.adjustedView && this.adjustedView !== currentView) {
      if (currentView === VIEWS.TIME) {
        hoursUp.focus();
      } else {
        var focusNode = node.querySelector('.rdtPicker .rdtActive') || node.querySelector('.rdtDay[tabindex="0"]') || node.querySelector('.rdtMonth[tabindex="0"]') || node.querySelector('.rdtYear[tabindex="0"]');

        if (focusNode) {
          focusNode.focus();
        }
      }
    }

    this.adjustedView = currentView;

    if (minutesDown) {
      minutesDown.addEventListener('keydown', this.closeUnfocused);
    }
  };

  _proto.addEventListeners = function addEventListeners() {
    var _this3 = this;

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

    if (node) {
      node.addEventListener('mousedown', this.onDatePickerClick);
      node.addEventListener('keydown', this.mouseDownByKeyboard);
      node.addEventListener('keyup', this.mouseUpByKeyboard);
      node.addEventListener('keypress', this.clickByKeyboard);

      _lodash.default.toArray(node.querySelectorAll(blurSelector)).forEach(function (item) {
        item.addEventListener('blur', _this3.closeUnfocused);
      });
    }
  };

  _proto.removeEventListeners = function removeEventListeners() {
    var _this4 = this;

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

    if (node) {
      node.removeEventListener('mousedown', this.onDatePickerClick);
      node.removeEventListener('keydown', this.mouseDownByKeyboard);
      node.removeEventListener('keyup', this.mouseUpByKeyboard);
      node.removeEventListener('keypress', this.clickByKeyboard);

      _lodash.default.toArray(node.querySelectorAll(blurSelector)).forEach(function (item) {
        item.removeEventListener('blur', _this4.closeUnfocused);
      });
    }
  };

  _proto.isFocused = function isFocused() {
    var node = _reactDom.default.findDOMNode(this);

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

  return BSDatePicker;
}(_reactDatetime.default);

exports.BSDatePicker = BSDatePicker;