"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DatePicker = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactTransitionGroup = require("react-transition-group");
var _dateFns = require("date-fns");
var _moment = _interopRequireDefault(require("moment"));
var _ClassNames = require("./ClassNames");
var _CustomNavBarElement = require("./CustomNavBarElement");
var _Styles = require("./Styles");
var _YearMonthPicker = require("../Pickers/YearMonthPicker");
var _excluded = ["className", "onChange", "onDayClick", "selectedDays", "disabledDays", "selectionMode", "month", "onMonthChange", "dateRequired", "firstDayOfWeek", "fixedWeeks", "modifiers", "renderDay"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
var formatWeekdayName = function formatWeekdayName(str) {
  return (0, _moment.default)(str).format("ddd").charAt(0);
};
var DatePicker = exports.DatePicker = function DatePicker(_ref) {
  var className = _ref.className,
    onChange = _ref.onChange,
    onDayClick = _ref.onDayClick,
    selectedDays = _ref.selectedDays,
    disabledDays = _ref.disabledDays,
    _ref$selectionMode = _ref.selectionMode,
    selectionMode = _ref$selectionMode === void 0 ? "daily" : _ref$selectionMode,
    _ref$month = _ref.month,
    month = _ref$month === void 0 ? new Date() : _ref$month,
    _ref$onMonthChange = _ref.onMonthChange,
    onMonthChange = _ref$onMonthChange === void 0 ? function () {
      return null;
    } : _ref$onMonthChange,
    _ref$dateRequired = _ref.dateRequired,
    dateRequired = _ref$dateRequired === void 0 ? false : _ref$dateRequired,
    _ref$firstDayOfWeek = _ref.firstDayOfWeek,
    firstDayOfWeek = _ref$firstDayOfWeek === void 0 ? 0 : _ref$firstDayOfWeek,
    _ref$fixedWeeks = _ref.fixedWeeks,
    fixedWeeks = _ref$fixedWeeks === void 0 ? true : _ref$fixedWeeks,
    defaultModifiers = _ref.modifiers,
    renderDay = _ref.renderDay,
    rest = _objectWithoutProperties(_ref, _excluded);
  var _useState = (0, _react.useState)(),
    _useState2 = _slicedToArray(_useState, 2),
    enteredTo = _useState2[0],
    setEnteredTo = _useState2[1];
  var _useState3 = (0, _react.useState)(),
    _useState4 = _slicedToArray(_useState3, 2),
    enteredFrom = _useState4[0],
    setEnteredFrom = _useState4[1];
  var _useState5 = (0, _react.useState)(),
    _useState6 = _slicedToArray(_useState5, 2),
    stopScroll = _useState6[0],
    setStopScroll = _useState6[1];
  var _useState7 = (0, _react.useState)(true),
    _useState8 = _slicedToArray(_useState7, 2),
    direction = _useState8[0],
    setDirection = _useState8[1];
  var _useState9 = (0, _react.useState)(function () {
      return (selectedDays === null || selectedDays === void 0 ? void 0 : selectedDays.from) instanceof Date && (selectedDays === null || selectedDays === void 0 ? void 0 : selectedDays.to) instanceof Date;
    }),
    _useState10 = _slicedToArray(_useState9, 2),
    isPreselected = _useState10[0],
    setIsPreselected = _useState10[1];
  var _useState11 = (0, _react.useState)(selectionMode === "quarterly" || selectionMode === "monthly"),
    _useState12 = _slicedToArray(_useState11, 2),
    showMonthPicker = _useState12[0],
    setShowMonthPicker = _useState12[1];
  var _useState13 = (0, _react.useState)(defaultModifiers),
    _useState14 = _slicedToArray(_useState13, 2),
    modifiers = _useState14[0],
    setModifiers = _useState14[1];
  var week = firstDayOfWeek === 0 ? "week" : "isoWeek";
  (0, _react.useEffect)(function () {
    if (enteredFrom instanceof Date && enteredTo instanceof Date) {
      setModifiers(function (prev) {
        return _objectSpread(_objectSpread({}, prev), {}, {
          hovered: {
            from: enteredFrom,
            to: enteredTo
          }
        });
      });
    } else {
      setModifiers(defaultModifiers);
    }
  }, [enteredTo, enteredFrom, defaultModifiers]);
  var handleDayClick = (0, _react.useCallback)(function (day, modifiers) {
    if (onDayClick) {
      onDayClick(day, modifiers);
    }
    if (!onChange) {
      return;
    }
    if (month.getMonth() !== day.getMonth()) {
      onMonthChange(day);
    }
    if (modifiers["day_disabled"] || selectionMode === "none") {
      return;
    }
    // reset the selectedDays if the user clicks on the same day
    if (!dateRequired && (selectedDays !== null && selectedDays !== void 0 && selectedDays.from && (0, _moment.default)(day).isSame((0, _moment.default)(selectedDays.from), "day") || selectedDays !== null && selectedDays !== void 0 && selectedDays.to && (0, _moment.default)(day).isSame((0, _moment.default)(selectedDays.to), "day"))) {
      setEnteredTo(undefined);
      setEnteredFrom(undefined);
      return onChange(undefined);
    }
    if (selectionMode === "daily") {
      return onChange({
        from: day,
        to: day
      });
    }
    if (selectionMode === "weekly") {
      if (!dateRequired && selectedDays !== null && selectedDays !== void 0 && selectedDays.from && (0, _moment.default)(day).isSame((0, _moment.default)(selectedDays.from), week)) {
        return onChange(undefined);
      }
      return onChange({
        from: (0, _moment.default)(day).startOf(week).toDate(),
        to: (0, _moment.default)(day).endOf(week).toDate()
      });
    }
    if (selectionMode === "custom") {
      if (isPreselected) {
        setIsPreselected(false);
        return onChange({
          from: day,
          to: day
        });
      }
      if (!selectedDays || selectedDays !== null && selectedDays !== void 0 && selectedDays.from && selectedDays !== null && selectedDays !== void 0 && selectedDays.to && !(0, _moment.default)(selectedDays.from).isSame((0, _moment.default)(selectedDays.to))) {
        if (!dateRequired && selectedDays !== null && selectedDays !== void 0 && selectedDays.from && selectedDays !== null && selectedDays !== void 0 && selectedDays.to && (0, _moment.default)(day).isBetween((0, _moment.default)(selectedDays.from), (0, _moment.default)(selectedDays.to))) {
          setEnteredTo(day);
          setEnteredFrom(day);
          return onChange(undefined);
        }
        setEnteredFrom(day);
        return onChange({
          from: day,
          to: day
        });
      }
      if (selectedDays !== null && selectedDays !== void 0 && selectedDays.from && (0, _dateFns.isAfter)(day, selectedDays.from)) {
        setEnteredTo(undefined);
        setEnteredFrom(undefined);
        return onChange({
          from: selectedDays.from,
          to: day
        });
      }
      if (selectedDays !== null && selectedDays !== void 0 && selectedDays.to) {
        setEnteredTo(undefined);
        setEnteredFrom(undefined);
        return onChange({
          from: day,
          to: selectedDays.to
        });
      }
      return onChange({
        from: day,
        to: day
      });
    }
  }, [onDayClick, onChange, month, selectionMode, dateRequired, selectedDays, onMonthChange, week, isPreselected]);
  var isSelectedFirstDay = (0, _react.useCallback)(function () {
    if (selectionMode !== "custom") {
      return false;
    }
    if (selectedDays !== null && selectedDays !== void 0 && selectedDays.from && selectedDays !== null && selectedDays !== void 0 && selectedDays.to) {
      return (0, _moment.default)(selectedDays.from).isSame(selectedDays.to);
    }
  }, [selectionMode, selectedDays]);
  var handleDayMouseEnter = (0, _react.useCallback)(function (day) {
    if (isPreselected && selectionMode !== "weekly") {
      setEnteredTo(day);
      setEnteredFrom(day);
      return;
    }
    if (selectionMode === "daily") {
      setEnteredTo(day);
      setEnteredFrom(day);
    }
    if (selectionMode === "weekly") {
      setEnteredFrom((0, _moment.default)(day).startOf(week).toDate());
      setEnteredTo((0, _moment.default)(day).endOf(week).toDate());
    }
    if (selectionMode !== "weekly" && (!selectedDays || selectedDays !== null && selectedDays !== void 0 && selectedDays.from && selectedDays !== null && selectedDays !== void 0 && selectedDays.to && !(0, _moment.default)(selectedDays.from).isSame((0, _moment.default)(selectedDays.to)))) {
      setEnteredTo(day);
      setEnteredFrom(day);
    }
    if (isSelectedFirstDay() && selectedDays !== null && selectedDays !== void 0 && selectedDays.from) {
      setEnteredFrom(selectedDays.from);
      setEnteredTo(day);
    }
  }, [selectionMode, isSelectedFirstDay, selectedDays, week, isPreselected]);
  var onDayMouseLeave = (0, _react.useCallback)(function () {
    if (selectionMode === "weekly" || selectionMode === "daily" || selectionMode === "custom") {
      setEnteredFrom(undefined);
      setEnteredTo(undefined);
    }
  }, [setEnteredFrom, setEnteredTo, selectionMode]);
  var onWheel = (0, _react.useCallback)(function (e) {
    if (stopScroll && (new Date().getTime() - stopScroll.getTime()) / 1000 < 0.9) {
      return;
    }
    var nextMonth = showMonthPicker ? (0, _dateFns.addMonths)(month, 12) : (0, _dateFns.addMonths)(month, 1);
    var previousMonth = showMonthPicker ? (0, _dateFns.addMonths)(month, -12) : (0, _dateFns.addMonths)(month, -1);
    if (e.deltaY > 0.9) {
      setDirection(true);
      onMonthChange(nextMonth);
      setStopScroll(new Date());
    }
    if (e.deltaY < -0.9) {
      setDirection(false);
      onMonthChange(previousMonth);
      setStopScroll(new Date());
    }
  }, [stopScroll, showMonthPicker, month, onMonthChange]);
  var togglePicker = (0, _react.useCallback)(function () {
    if (selectionMode !== "monthly" && selectionMode !== "quarterly") {
      return setShowMonthPicker(!showMonthPicker);
    }
    setShowMonthPicker(true);
  }, [showMonthPicker, selectionMode]);
  var handleYearMonthChange = (0, _react.useCallback)(function (m) {
    if (onChange) {
      if (selectionMode === "monthly") {
        if (!dateRequired && selectedDays !== null && selectedDays !== void 0 && selectedDays.from && (0, _moment.default)(m).isSame((0, _moment.default)(selectedDays.from), "month")) {
          return onChange(undefined);
        }
        onChange({
          from: (0, _moment.default)(m).startOf("month").toDate(),
          to: (0, _moment.default)(m).endOf("month").toDate()
        });
      }
      if (selectionMode === "quarterly") {
        if (!dateRequired && selectedDays !== null && selectedDays !== void 0 && selectedDays.from && (0, _moment.default)(m).isSame((0, _moment.default)(selectedDays.from).startOf("quarter"), "quarter")) {
          return onChange(undefined);
        }
        onChange({
          from: (0, _moment.default)(m).startOf("quarter").toDate(),
          to: (0, _moment.default)(m).endOf("quarter").toDate()
        });
      }
    }
    onMonthChange(m);
  }, [onMonthChange, onChange, selectedDays, selectionMode, dateRequired]);
  var text = (0, _react.useMemo)(function () {
    if (showMonthPicker) {
      return "".concat(month.getFullYear());
    }
    return "".concat((0, _moment.default)(month).format("MMMM"), " ").concat((0, _moment.default)(month).isSame((0, _moment.default)(), "year") ? "" : month.getFullYear());
  }, [showMonthPicker, month]);
  var customNavBarElement = (0, _react.useCallback)(function (props) {
    return /*#__PURE__*/_react.default.createElement("div", {
      className: "c-DayPicker-wrapper"
    }, /*#__PURE__*/_react.default.createElement(_CustomNavBarElement.CustomNavBarElement, _extends({}, props, {
      showMonthPicker: showMonthPicker,
      month: month,
      onChangeDirection: setDirection,
      onMonthChange: onMonthChange,
      onClick: togglePicker
    })), /*#__PURE__*/_react.default.createElement(_YearMonthPicker.YearMonthPicker, _extends({}, props, {
      text: text,
      onClick: togglePicker,
      month: month,
      selectedDays: selectedDays,
      onChange: handleYearMonthChange,
      isShown: showMonthPicker,
      selectionMode: selectionMode
    })));
  }, [showMonthPicker, month, onMonthChange, togglePicker, text, selectedDays, handleYearMonthChange, selectionMode]);
  var onKeyDownCallback = (0, _react.useCallback)(function (e) {
    // Right Arrow
    if (e.key === "ArrowRight") {
      setDirection(true);
      if (showMonthPicker) {
        onMonthChange(new Date(month.getFullYear() + 1, month.getMonth()));
      } else {
        onMonthChange(new Date(month.getFullYear(), month.getMonth() + 1));
      }
    }
    // Left Arrow
    if (e.key === "ArrowLeft") {
      setDirection(false);
      if (showMonthPicker) {
        onMonthChange(new Date(month.getFullYear() - 1, month.getMonth()));
      } else {
        onMonthChange(new Date(month.getFullYear(), month.getMonth() - 1));
      }
    }
    // Up Arrow
    if (e.key === "ArrowUp") {
      setDirection(true);
      onMonthChange(new Date(month.getFullYear() + 1, month.getMonth()));
    }
    // Down Arrow
    if (e.key === "ArrowDown") {
      setDirection(false);
      onMonthChange(new Date(month.getFullYear() - 1, month.getMonth()));
    }
  }, [showMonthPicker, onMonthChange, month]);
  (0, _react.useEffect)(function () {
    document.addEventListener("keydown", onKeyDownCallback);
    return function () {
      document.removeEventListener("keydown", onKeyDownCallback);
    };
  }, [month, onMonthChange, showMonthPicker, onKeyDownCallback]);
  var selected = (0, _react.useMemo)(function () {
    var dates = [];
    if (!(selectedDays !== null && selectedDays !== void 0 && selectedDays.from)) return [];

    // If from and to dates are the same, return an array with one item
    if ((0, _moment.default)(selectedDays === null || selectedDays === void 0 ? void 0 : selectedDays.from).isSame(selectedDays === null || selectedDays === void 0 ? void 0 : selectedDays.to, "day")) {
      dates.push(selectedDays === null || selectedDays === void 0 ? void 0 : selectedDays.from);
      return dates;
    }
    var currentDate = (0, _moment.default)(selectedDays === null || selectedDays === void 0 ? void 0 : selectedDays.from);
    while (currentDate.isSameOrBefore(selectedDays === null || selectedDays === void 0 ? void 0 : selectedDays.to, "day")) {
      dates.push(currentDate.toDate());
      currentDate = currentDate.add(1, "days");
    }
    return dates;
  }, [selectedDays === null || selectedDays === void 0 ? void 0 : selectedDays.from, selectedDays === null || selectedDays === void 0 ? void 0 : selectedDays.to]);
  return /*#__PURE__*/_react.default.createElement(_Styles.StyledDatePicker, {
    className: "c-date-picker-wrapper",
    onWheel: onWheel
  }, /*#__PURE__*/_react.default.createElement(_reactTransitionGroup.SwitchTransition, {
    mode: "out-in"
  }, /*#__PURE__*/_react.default.createElement(_Styles.StyledDatePickerCSSTransition, {
    key: showMonthPicker ? month.getFullYear() : month.getMonth(),
    timeout: 300,
    classNames: "c-date-picker__animation",
    $direction: direction
  }, /*#__PURE__*/_react.default.createElement(_Styles.StyledDayPicker, _extends({}, rest, {
    mode: "multiple",
    showOutsideDays: true,
    disabled: disabledDays,
    selected: selected,
    onDayClick: handleDayClick,
    modifiers: modifiers,
    onDayMouseEnter: handleDayMouseEnter,
    onDayMouseLeave: onDayMouseLeave,
    className: className,
    $isYearlyView: showMonthPicker,
    month: month,
    components: {
      Caption: customNavBarElement,
      DayContent: renderDay
    },
    classNames: _ClassNames.customClassNames,
    modifiersClassNames: _ClassNames.modifiersClassNames,
    fixedWeeks: fixedWeeks,
    weekStartsOn: firstDayOfWeek,
    formatters: {
      formatWeekdayName: formatWeekdayName
    }
  })))));
};
DatePicker.displayName = "DatePicker";
//# sourceMappingURL=DatePicker.js.map