"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SelectDate = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _moment = _interopRequireDefault(require("moment"));
var _DatePickerForm = require("./DatePickerForm");
var _SelectDateTarget = require("./SelectDateTarget");
var _Styles = require("./Styles");
var _dateUtils = require("../../utils/dateUtils");
var _Localization = require("../Localization");
var _Menu = require("../Menu/Menu");
var _Tooltip = require("../Tooltip/Tooltip");
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 _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; }
var getUtcTimestampFromDate = function getUtcTimestampFromDate(date) {
  return _moment.default.utc([date.getFullYear(), date.getMonth(), date.getDate()]).unix();
};
var isDayInRange = function isDayInRange(day, data) {
  if (data.repeating) {
    var from = new Date(day.getFullYear(), data.from.getMonth(), data.from.getDate());
    var to = new Date(day.getFullYear(), data.to.getMonth(), data.to.getDate());
    return day >= from && day <= to;
  }
  return day >= data.from && day <= data.to;
};
var SelectDate = exports.SelectDate = function SelectDate(_ref) {
  var _ref$changeMode = _ref.changeMode,
    mode = _ref$changeMode === void 0 ? "instant" : _ref$changeMode,
    _ref$trigger = _ref.trigger,
    labelType = _ref$trigger === void 0 ? "text" : _ref$trigger,
    _ref$saveButtonText = _ref.saveButtonText,
    saveButtonText = _ref$saveButtonText === void 0 ? "Save" : _ref$saveButtonText,
    _ref$cancelButtonText = _ref.cancelButtonText,
    cancelButtonText = _ref$cancelButtonText === void 0 ? "Cancel" : _ref$cancelButtonText,
    _ref$clearButtonText = _ref.clearButtonText,
    clearButtonText = _ref$clearButtonText === void 0 ? "Clear" : _ref$clearButtonText,
    _ref$modalHeaderText = _ref.modalHeaderText,
    modalHeaderText = _ref$modalHeaderText === void 0 ? "Discard changes?" : _ref$modalHeaderText,
    _ref$modalDiscardMess = _ref.modalDiscardMessage,
    modalDiscardMessage = _ref$modalDiscardMess === void 0 ? "All unsaved changes will be lost." : _ref$modalDiscardMess,
    _ref$modalDiscardBtnT = _ref.modalDiscardBtnText,
    modalDiscardBtnText = _ref$modalDiscardBtnT === void 0 ? "OK" : _ref$modalDiscardBtnT,
    _ref$modalCancelBtnTe = _ref.modalCancelBtnText,
    modalCancelBtnText = _ref$modalCancelBtnTe === void 0 ? "Cancel" : _ref$modalCancelBtnTe,
    onDayClick = _ref.onDayClick,
    onSave = _ref.onSave,
    onCancel = _ref.onCancel,
    onToggleDatePicker = _ref.onToggleDatePicker,
    _ref$required = _ref.required,
    dateRequired = _ref$required === void 0 ? false : _ref$required,
    _ref$defaultTimezoneA = _ref.defaultTimezoneAware,
    defaultTimezoneAware = _ref$defaultTimezoneA === void 0 ? false : _ref$defaultTimezoneA,
    _ref$longDateFormat = _ref.longDateFormat,
    longDateFormat = _ref$longDateFormat === void 0 ? false : _ref$longDateFormat,
    _ref$defaultShowDateP = _ref.defaultShowDatePicker,
    defaultShowDatePicker = _ref$defaultShowDateP === void 0 ? false : _ref$defaultShowDateP,
    _ref$firstDayOfWeek = _ref.firstDayOfWeek,
    firstDayOfWeek = _ref$firstDayOfWeek === void 0 ? 0 : _ref$firstDayOfWeek,
    selectedDays = _ref.selectedDays,
    _ref$selectionMode = _ref.selectionMode,
    selectionMode = _ref$selectionMode === void 0 ? "custom" : _ref$selectionMode,
    menuClassName = _ref.menuClassName,
    targetClassName = _ref.targetClassName,
    icon = _ref.icon,
    _ref$defaultLabelText = _ref.defaultLabelText,
    defaultLabelText = _ref$defaultLabelText === void 0 ? "Set..." : _ref$defaultLabelText,
    targetTextClassName = _ref.targetTextClassName,
    targetIconClassName = _ref.targetIconClassName,
    backgroundElementClass = _ref.backgroundElementClass,
    passedDateFormat = _ref.dateFormat,
    defaultMonth = _ref.defaultMonth,
    _ref$daysToModify = _ref.daysToModify,
    daysToModify = _ref$daysToModify === void 0 ? [] : _ref$daysToModify,
    _ref$weekends = _ref.weekends,
    weekends = _ref$weekends === void 0 ? [] : _ref$weekends,
    _ref$weekendLabel = _ref.weekendLabel,
    weekendLabel = _ref$weekendLabel === void 0 ? "Weekend" : _ref$weekendLabel,
    _ref$nonWorkingDaysOf = _ref.nonWorkingDaysOfWeek,
    nonWorkingDaysOfWeek = _ref$nonWorkingDaysOf === void 0 ? [] : _ref$nonWorkingDaysOf,
    _ref$nonWorkingDaysOf2 = _ref.nonWorkingDaysOfWeekLabel,
    nonWorkingDaysOfWeekLabel = _ref$nonWorkingDaysOf2 === void 0 ? "Unavailable" : _ref$nonWorkingDaysOf2,
    _ref$weekendIsSelecta = _ref.weekendIsSelectable,
    weekendIsSelectable = _ref$weekendIsSelecta === void 0 ? false : _ref$weekendIsSelecta,
    tooltipText = _ref.tooltipText,
    popperTooltipClassName = _ref.popperTooltipClassName,
    popperClassName = _ref.popperClassName,
    popperTooltipStyle = _ref.popperTooltipStyle,
    position = _ref.position,
    disableDaysBefore = _ref.disableDaysBefore;
  var _useState = (0, _react.useState)(defaultTimezoneAware),
    _useState2 = _slicedToArray(_useState, 2),
    timezoneAware = _useState2[0],
    setTimezoneAware = _useState2[1];
  var localization = (0, _Localization.useLocalization)();
  var dateFormat = passedDateFormat ? passedDateFormat : localization.dateFormat;
  var labelText = (0, _react.useMemo)(function () {
    if (!selectedDays) {
      return defaultLabelText;
    } else {
      var endDate = timezoneAware ? _moment.default.unix(selectedDays.to).local() : _moment.default.unix(selectedDays.to).utc();
      var startDate = timezoneAware ? _moment.default.unix(selectedDays.from).local() : _moment.default.unix(selectedDays.from).utc();
      var formattedEndDate = (0, _dateUtils.formatDate)(endDate, dateFormat, longDateFormat);
      var formattedStartDate = (0, _dateUtils.formatDate)(startDate, dateFormat, longDateFormat);
      if (selectedDays.from === selectedDays.to) {
        return formattedEndDate;
      }
      return "".concat(formattedStartDate, " - ").concat(formattedEndDate);
    }
  }, [selectedDays, dateFormat, timezoneAware, defaultLabelText, longDateFormat]);
  var modifiedDates = (0, _react.useMemo)(function () {
    if (typeof selectedDays === "object" && !!selectedDays.from && !!selectedDays.to) {
      if (timezoneAware) {
        return {
          from: _moment.default.unix(selectedDays.from).toDate(),
          to: _moment.default.unix(selectedDays.to).toDate()
        };
      }
      var offsetFrom = _moment.default.unix(selectedDays.from).utcOffset() * 60;
      var offsetTo = _moment.default.unix(selectedDays.to).utcOffset() * 60;
      return {
        from: new Date((selectedDays.from - offsetFrom) * 1000),
        to: new Date((selectedDays.to - offsetTo) * 1000)
      };
    }
  }, [selectedDays, timezoneAware]);
  var handleModifiedSave = (0, _react.useCallback)(function (selectedDates) {
    setTimezoneAware(false);
    if (typeof onSave === "function") {
      if (typeof selectedDates === "object" && Object.prototype.hasOwnProperty.call(selectedDates, "from") && Object.prototype.hasOwnProperty.call(selectedDates, "to")) {
        onSave({
          from: getUtcTimestampFromDate(selectedDates.from),
          to: getUtcTimestampFromDate(selectedDates.to)
        });
      } else {
        onSave(undefined);
      }
    }
  }, [onSave]);
  var getDefaultMonth = (0, _react.useCallback)(function () {
    var date = new Date();
    if (typeof selectedDays === "object" && !!selectedDays.from) {
      date = timezoneAware ? new Date(selectedDays.from * 1000) : new Date((selectedDays.from - _moment.default.unix(selectedDays.from).utcOffset() * 60) * 1000);
    } else if (defaultMonth) {
      date = defaultMonth;
    }

    // forcing second day in month
    return new Date(date.getFullYear(), date.getMonth(), 2);
  }, [defaultMonth, selectedDays, timezoneAware]);
  var _useState3 = (0, _react.useState)(getDefaultMonth),
    _useState4 = _slicedToArray(_useState3, 2),
    month = _useState4[0],
    setMonth = _useState4[1];
  var handleMonthChange = (0, _react.useCallback)(function (month) {
    setMonth(month);
  }, [setMonth]);
  var _useState5 = (0, _react.useState)(modifiedDates),
    _useState6 = _slicedToArray(_useState5, 2),
    newDates = _useState6[0],
    setNewDates = _useState6[1];
  var _useState7 = (0, _react.useState)(false),
    _useState8 = _slicedToArray(_useState7, 2),
    showDiscardModal = _useState8[0],
    setShowDiscardModal = _useState8[1];
  var _useState9 = (0, _react.useState)(defaultShowDatePicker),
    _useState10 = _slicedToArray(_useState9, 2),
    showDatePicker = _useState10[0],
    setShowDatePicker = _useState10[1];
  var disabledSaveButton = (0, _react.useMemo)(function () {
    return (modifiedDates === null || modifiedDates === void 0 ? void 0 : modifiedDates.from) === (newDates === null || newDates === void 0 ? void 0 : newDates.from) && (modifiedDates === null || modifiedDates === void 0 ? void 0 : modifiedDates.to) === (newDates === null || newDates === void 0 ? void 0 : newDates.to);
  }, [modifiedDates, newDates]);
  (0, _react.useEffect)(function () {
    setShowDatePicker(defaultShowDatePicker);
  }, [defaultShowDatePicker]);
  (0, _react.useEffect)(function () {
    setNewDates(modifiedDates);
  }, [modifiedDates]);
  (0, _react.useEffect)(function () {
    typeof onToggleDatePicker === "function" && onToggleDatePicker(showDatePicker);
  }, [showDatePicker, onToggleDatePicker]);
  (0, _react.useEffect)(function () {
    if (!showDatePicker) {
      setMonth(getDefaultMonth());
    }
  }, [showDatePicker, getDefaultMonth]);
  var handleSave = (0, _react.useCallback)(function () {
    handleModifiedSave(newDates);
    setShowDatePicker(false);
  }, [newDates, handleModifiedSave]);
  var handleChange = (0, _react.useCallback)(function (dates) {
    if (mode !== "atomic") {
      handleModifiedSave(dates);
    }
    setNewDates(dates);
  }, [mode, handleModifiedSave]);
  var handleBeforeCloseMenu = (0, _react.useCallback)(function () {
    var result = true;
    if (modifiedDates && !newDates || !modifiedDates && newDates) {
      result = false;
    }
    var selectedDaysFrom = modifiedDates === null || modifiedDates === void 0 ? void 0 : modifiedDates.from;
    var selectedDaysTo = modifiedDates === null || modifiedDates === void 0 ? void 0 : modifiedDates.to;
    var newDatesFrom = newDates === null || newDates === void 0 ? void 0 : newDates.from;
    var newDatesTo = newDates === null || newDates === void 0 ? void 0 : newDates.to;
    if (selectedDaysFrom && newDatesFrom && selectedDaysTo && newDatesTo && ((0, _moment.default)(selectedDaysFrom).format("DD-MM-YYYY") !== (0, _moment.default)(newDatesFrom).format("DD-MM-YYYY") || (0, _moment.default)(selectedDaysTo).format("DD-MM-YYYY") !== (0, _moment.default)(newDatesTo).format("DD-MM-YYYY"))) {
      result = false;
    }
    if (!result) {
      setShowDiscardModal(true);
    }
    return result;
  }, [modifiedDates, newDates]);
  var handleClose = (0, _react.useCallback)(function () {
    if (mode !== "atomic" || handleBeforeCloseMenu()) {
      typeof onCancel === "function" && onCancel();
      setShowDatePicker(false);
    }
  }, [mode, onCancel, handleBeforeCloseMenu]);
  var handleCancel = (0, _react.useCallback)(function (event) {
    event && event.preventDefault();
    return handleClose();
  }, [handleClose]);
  var handleShowDatePicker = (0, _react.useCallback)(function () {
    setShowDatePicker(!showDatePicker);
  }, [showDatePicker]);
  var handleCloseDiscardModal = (0, _react.useCallback)(function () {
    setShowDiscardModal(false);
  }, []);
  var handleClear = (0, _react.useCallback)(function () {
    if (!dateRequired) {
      setNewDates(undefined);
      if (mode === "instant") {
        handleModifiedSave(undefined);
      }
    }
  }, [mode, dateRequired, handleModifiedSave]);
  var handleSaveDiscardModal = (0, _react.useCallback)(function () {
    setNewDates(modifiedDates);
    setShowDiscardModal(false);
    setShowDatePicker(false);
  }, [modifiedDates]);
  var modifiers = (0, _react.useMemo)(function () {
    var userAvailabilities = daysToModify.filter(function (data) {
      return data.type === "user_day_off";
    });
    var globalDaysOff = daysToModify.filter(function (data) {
      return data.type === "global_day_off";
    });
    var selectableGlobalDaysOff = daysToModify.filter(function (data) {
      return data.type === "selectable_global_day_off";
    });
    return {
      userAvailability: function userAvailability(day) {
        // construct new date because react-day-picker returns date with hours set
        var currentDay = new Date(day.getFullYear(), day.getMonth(), day.getDate());
        return userAvailabilities.some(function (data) {
          return isDayInRange(currentDay, data);
        });
      },
      weekend: function weekend(day) {
        return weekends.some(function (value) {
          return day.getDay() === value;
        });
      },
      nonWorkingDay: function nonWorkingDay(day) {
        // return true if day is weekend day
        if (weekends.some(function (value) {
          return value === day.getDay();
        })) {
          return true;
        }
        var nonWorkingDays = [...selectableGlobalDaysOff, ...globalDaysOff];
        var currentDay = new Date(day.getFullYear(), day.getMonth(), day.getDate());
        return nonWorkingDays.some(function (data) {
          return isDayInRange(currentDay, data);
        });
      },
      day_disabled: function day_disabled(day) {
        if (disableDaysBefore) {
          if (day.toJSON().slice(0, 10) < disableDaysBefore.toJSON().slice(0, 10)) {
            return true;
          }
        }
        // return true if day is weekend day
        if (!weekendIsSelectable && weekends.some(function (value) {
          return value === day.getDay();
        })) {
          return true;
        }
        // construct new date because react-day-picker returns date with hours set
        var currentDay = new Date(day.getFullYear(), day.getMonth(), day.getDate());
        return globalDaysOff.some(function (data) {
          return isDayInRange(currentDay, data);
        });
      },
      nonWorkingDaysOfWeek: {
        dayOfWeek: nonWorkingDaysOfWeek
      }
    };
  }, [daysToModify, nonWorkingDaysOfWeek, weekends, disableDaysBefore, weekendIsSelectable]);
  var renderDay = (0, _react.useCallback)(function (props) {
    var titles = [];
    if (weekends.some(function (value) {
      return props.date.getDay() === value;
    })) {
      titles.push(weekendLabel);
    }
    if (nonWorkingDaysOfWeek.includes(props.date.getDay())) {
      titles.push(nonWorkingDaysOfWeekLabel);
    }

    // construct new date because react-day-picker returns date with hours set
    var currentDay = new Date(props.date.getFullYear(), props.date.getMonth(), props.date.getDate());
    daysToModify.forEach(function (data) {
      if (isDayInRange(currentDay, data)) {
        titles.push(data.title);
      }
    });
    var child = /*#__PURE__*/_react.default.createElement("div", {
      className: "c-DayPicker-Day-Number"
    }, props.date.getDate());
    if (titles.length) {
      var title = /*#__PURE__*/_react.default.createElement("div", {
        key: "title-wrapper-".concat(props.date.getDate())
      }, titles.map(function (title, index) {
        return /*#__PURE__*/_react.default.createElement("div", {
          key: "title-text-".concat(index)
        }, title);
      }));
      return /*#__PURE__*/_react.default.createElement(_Tooltip.Tooltip, {
        title: title,
        popperTooltipClassName: popperTooltipClassName,
        popperTooltipStyle: popperTooltipStyle
      }, child);
    }
    return child;
  }, [weekends, nonWorkingDaysOfWeek, daysToModify, weekendLabel, nonWorkingDaysOfWeekLabel, popperTooltipClassName, popperTooltipStyle]);
  var renderDatePickerForm = (0, _react.useCallback)(function () {
    return /*#__PURE__*/_react.default.createElement(_DatePickerForm.DatePickerForm, {
      onMonthChange: handleMonthChange,
      month: month,
      mode: mode,
      selectionMode: selectionMode,
      dateRequired: dateRequired,
      selectedDays: newDates,
      firstDayOfWeek: firstDayOfWeek,
      saveButtonText: saveButtonText,
      cancelButtonText: cancelButtonText,
      clearButtonText: clearButtonText,
      onDayClick: onDayClick,
      onSave: handleSave,
      onChange: handleChange,
      onCancel: handleCancel,
      onClear: handleClear,
      disabledSaveButton: disabledSaveButton,
      modifiers: modifiers,
      renderDay: renderDay
    });
  }, [handleMonthChange, month, mode, selectionMode, dateRequired, newDates, firstDayOfWeek, saveButtonText, cancelButtonText, clearButtonText, onDayClick, handleSave, handleChange, handleCancel, handleClear, disabledSaveButton, modifiers, renderDay]);
  var renderTargetEl = (0, _react.useMemo)(function () {
    if (labelType === "icon" && icon) {
      return /*#__PURE__*/_react.default.createElement(_SelectDateTarget.SelectDateTarget, {
        icon: icon,
        title: tooltipText,
        targetIconClassName: targetIconClassName,
        forceHideTooltip: showDatePicker,
        popperTooltipClassName: popperTooltipClassName,
        popperTooltipStyle: popperTooltipStyle,
        active: showDatePicker
      });
    }
    if (typeof labelType === "function") {
      return labelType(labelText);
    }
    return /*#__PURE__*/_react.default.createElement(_Styles.StyledSelectDateButton, {
      type: "button",
      className: (0, _classnames.default)("date-picker-target", targetClassName)
    }, /*#__PURE__*/_react.default.createElement("span", {
      className: targetTextClassName
    }, labelText));
  }, [icon, labelText, labelType, popperTooltipClassName, popperTooltipStyle, showDatePicker, targetClassName, targetIconClassName, targetTextClassName, tooltipText]);
  return /*#__PURE__*/_react.default.createElement(_Styles.StyledSelectDate, {
    className: "select-date"
  }, labelType !== "inline" ? /*#__PURE__*/_react.default.createElement(_Menu.Menu, {
    target: renderTargetEl,
    open: showDatePicker,
    onOpen: handleShowDatePicker,
    onBeforeClose: handleBeforeCloseMenu,
    onClose: handleClose,
    position: position,
    menuClassName: menuClassName,
    popperClassName: popperClassName,
    backgroundElementClass: backgroundElementClass
  }, renderDatePickerForm()) : renderDatePickerForm(), mode === "atomic" ? /*#__PURE__*/_react.default.createElement(_Styles.StyledConfirmDialog, {
    className: "modal-select-date",
    open: showDiscardModal,
    onCancel: handleCloseDiscardModal,
    onConfirm: handleSaveDiscardModal,
    dialogTitle: modalHeaderText,
    dialogContent: modalDiscardMessage,
    cancelBtnText: modalCancelBtnText,
    confirmBtnText: modalDiscardBtnText
  }) : null);
};
SelectDate.displayName = "SelectDate";
//# sourceMappingURL=SelectDate.js.map