"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useDatePickerClearable = void 0;
var _react = require("react");
var _reactIntl = require("react-intl");
var _dateFns = require("date-fns");
var _Hooks = require("../../../../common/Hooks");
var _dateUtils = require("../../shared/dateUtils");
var _constants = require("../../shared/constants");
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 formatInputValue = function formatInputValue(selectedDate, dateFormat, locale) {
  if (selectedDate) {
    return (0, _dateFns.format)(selectedDate, dateFormat, {
      locale: locale
    });
  }
  return '';
};
var handleSelectDate = function handleSelectDate(date, selectedDate, selectedEndDate, allowSingleDayRange, isRangePicker) {
  if (!selectedDate || !isRangePicker) return [date, null];
  if ((0, _dateFns.isBefore)(date, selectedDate)) return [date, selectedEndDate];
  var swapDate = !selectedEndDate && (0, _dateFns.isBefore)(date, selectedDate);
  if (swapDate) return [date, selectedDate];
  if ((0, _dateFns.isSameDay)(date, selectedDate)) {
    if (!allowSingleDayRange) {
      return [selectedDate, null];
    }
    return [selectedDate, selectedDate];
  }
  if (selectedEndDate && (0, _dateFns.isSameDay)(date, selectedEndDate)) {
    if (!allowSingleDayRange) {
      return [selectedDate, null];
    }
    return [selectedEndDate, selectedEndDate];
  }
  return [selectedDate, date];
};
var useDatePickerClearable = exports.useDatePickerClearable = function useDatePickerClearable(_ref) {
  var id = _ref.id,
    selectedDateProp = _ref.selectedDateProp,
    enableDate = _ref.enableDate,
    disableDate = _ref.disableDate,
    onChange = _ref.onChange,
    onBlur = _ref.onBlur,
    allowDateUpdateOnType = _ref.allowDateUpdateOnType,
    _ref$allowSingleDayRa = _ref.allowSingleDayRange,
    allowSingleDayRange = _ref$allowSingleDayRa === void 0 ? true : _ref$allowSingleDayRa,
    _ref$noOfMonthsInCale = _ref.noOfMonthsInCalendarView,
    dateRange = _ref$noOfMonthsInCale === void 0 ? 1 : _ref$noOfMonthsInCale;
  var _useIntl = (0, _reactIntl.useIntl)(),
    locale = _useIntl.locale;
  var _useState = (0, _react.useState)(selectedDateProp || null),
    _useState2 = _slicedToArray(_useState, 2),
    selectedDate = _useState2[0],
    setSelectedDate = _useState2[1];
  var _useState3 = (0, _react.useState)(false),
    _useState4 = _slicedToArray(_useState3, 2),
    invalidDate = _useState4[0],
    setInvalidDate = _useState4[1];
  var _useState5 = (0, _react.useState)(formatInputValue(selectedDate, (0, _dateUtils.getDateFormat)(locale), (0, _dateUtils.getLocale)(locale))),
    _useState6 = _slicedToArray(_useState5, 2),
    inputValue = _useState6[0],
    setInputValue = _useState6[1];
  var _useState7 = (0, _react.useState)((0, _dateFns.setDate)(selectedDateProp && new Date(selectedDateProp) || (0, _dateFns.startOfDay)(new Date()), 1)),
    _useState8 = _slicedToArray(_useState7, 2),
    viewedDate = _useState8[0],
    setViewedDate = _useState8[1];
  var previousInputValue = (0, _Hooks.usePrevious)(inputValue);
  (0, _react.useEffect)(function () {
    if (selectedDateProp) {
      setSelectedDate(selectedDateProp);
      var controlledInputValue = formatInputValue(selectedDateProp, (0, _dateUtils.getDateFormat)(locale), (0, _dateUtils.getLocale)(locale));
      setInputValue(controlledInputValue);
      setViewedDate((0, _dateFns.setDate)(selectedDateProp, 1));
    }
  }, [locale, selectedDateProp]);
  (0, _react.useEffect)(function () {
    if (previousInputValue && !inputValue) {
      setSelectedDate(null);
    }
    setInvalidDate(false);
  }, [inputValue, previousInputValue]);
  var allowedDate = (0, _react.useCallback)(function (date) {
    if (date && disableDate && disableDate(date)) {
      setInvalidDate(true);
      return null;
    }
    if (date && enableDate && !enableDate(date)) {
      setInvalidDate(true);
      return null;
    }
    return date;
  }, [disableDate, enableDate]);
  var handleDateClick = (0, _react.useCallback)(function (date) {
    var _handleSelectDate = handleSelectDate(date, selectedDate, null, allowSingleDayRange, false),
      _handleSelectDate2 = _slicedToArray(_handleSelectDate, 1),
      startDate = _handleSelectDate2[0];
    if (selectedDate && (0, _dateFns.isSameDay)(startDate, selectedDate)) return;
    var dateString = formatInputValue(startDate, (0, _dateUtils.getDateFormat)(locale), (0, _dateUtils.getLocale)(locale));
    setSelectedDate(startDate);
    setInputValue(dateString);
    if (onChange) onChange(startDate);
  }, [selectedDate, allowSingleDayRange, locale, onChange]);
  var onDateClick = (0, _react.useCallback)(function (date) {
    if (date && !(0, _dateFns.isWithinInterval)(date, {
      start: viewedDate,
      end: (0, _dateFns.subMilliseconds)((0, _dateFns.addMonths)(viewedDate, dateRange), 1)
    })) {
      var newViewedDate = (0, _dateFns.isBefore)(date, viewedDate) ? (0, _dateFns.subMonths)(viewedDate, 1) : (0, _dateFns.addMonths)(viewedDate, 1);
      setViewedDate(newViewedDate);
    }
    handleDateClick(date);
  }, [viewedDate, dateRange, handleDateClick]);
  var handleInputSubmit = (0, _react.useCallback)(function () {
    var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [],
      _ref3 = _slicedToArray(_ref2, 1),
      _ref3$ = _ref3[0],
      startDateValue = _ref3$ === void 0 ? inputValue : _ref3$;
    var _ref4 = [(0, _dateUtils.parseDateString)(startDateValue, locale)],
      parsedStartDate = _ref4[0];
    var _ref5 = [allowedDate(parsedStartDate)],
      startDate = _ref5[0];
    if (startDate) {
      setSelectedDate(startDate);
      if (startDate && !(0, _dateFns.isWithinInterval)(startDate, {
        start: viewedDate,
        end: (0, _dateFns.subMilliseconds)((0, _dateFns.addMonths)(viewedDate, dateRange), 1)
      })) {
        setViewedDate((0, _dateFns.setDate)(startDate, 1));
      }
      var dateString = formatInputValue(startDate, (0, _dateUtils.getDateFormat)(locale), (0, _dateUtils.getLocale)(locale));
      setInputValue(dateString);
      if (onChange) onChange(startDate);
      if (onBlur) onBlur(startDate);
    }
  }, [inputValue, locale, allowedDate, viewedDate, dateRange, onChange, onBlur]);
  var onMonthChange = (0, _react.useCallback)(function (index) {
    setViewedDate((0, _dateFns.setMonth)(viewedDate, index));
  }, [viewedDate, setViewedDate]);
  var onYearChange = (0, _react.useCallback)(function (year) {
    setViewedDate((0, _dateFns.setYear)(viewedDate, year));
  }, [viewedDate, setViewedDate]);
  var handleInputOnChange = (0, _react.useCallback)(function (event) {
    var _event$target = event.target,
      value = _event$target.value,
      elementId = _event$target.id;
    if (value === '' && onChange) {
      setInputValue(value);
      onChange(undefined);
      return;
    }
    var assignedValues = function () {
      if (elementId === (0, _constants.INPUT_ID_START)(id)) {
        setInputValue(value);
        return [value];
      }
      if (elementId === (0, _constants.INPUT_ID_RANGE)(id)) {
        var _value$split$map = value.split('-').map(function (v) {
            return v.trim();
          }),
          _value$split$map2 = _slicedToArray(_value$split$map, 1),
          startDateValue = _value$split$map2[0];
        setInputValue(startDateValue);
        return [startDateValue];
      }
      setInputValue(value);
      return [value];
    }();
    if (allowDateUpdateOnType) {
      handleInputSubmit(assignedValues);
    }
  }, [allowDateUpdateOnType, handleInputSubmit, id, onChange]);
  var handleInputOnBlur = (0, _react.useCallback)(function () {
    handleInputSubmit();
  }, [handleInputSubmit]);
  var handleInputKeyDown = (0, _react.useCallback)(function (event) {
    if (event.key === 'Enter') handleInputSubmit();
  }, [handleInputSubmit]);
  var clearDate = (0, _react.useCallback)(function () {
    setInputValue('');
  }, []);
  return {
    selectedDate: selectedDate,
    inputValue: inputValue,
    handleInputKeyDown: handleInputKeyDown,
    handleInputOnChange: handleInputOnChange,
    handleInputOnBlur: handleInputOnBlur,
    onMonthChange: onMonthChange,
    onYearChange: onYearChange,
    onDateClick: onDateClick,
    viewedDate: viewedDate,
    clearDate: clearDate,
    invalidDate: invalidDate
  };
};