"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

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

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

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

var _getLocale = require("../../../utils/getLocale");

var _popup = _interopRequireDefault(require("../../popup"));

var _context = require("../context");

var _utils = require("../utils");

var _operations = _interopRequireDefault(require("./components/operations"));

var _placeholder = _interopRequireDefault(require("./components/placeholder"));

var _picker = _interopRequireDefault(require("../picker"));

var _pickerTrigger = _interopRequireDefault(require("./components/picker-trigger"));

var _shortcuts = _interopRequireDefault(require("./components/shortcuts"));

require("./index.css");

var _excluded = ["onChange", "format", "values", "picker", "children", "popupPlacement", "direction", "onPopupVisibleChange", "visible", "canEmpty", "className"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || 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 _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(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

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 RangePicker = function RangePicker(props) {
  var onChange = props.onChange,
      _props$format = props.format,
      format = _props$format === void 0 ? _utils.PickerFormat : _props$format,
      _props$values = props.values,
      values = _props$values === void 0 ? [] : _props$values,
      _props$picker = props.picker,
      picker = _props$picker === void 0 ? 'date' : _props$picker,
      children = props.children,
      _props$popupPlacement = props.popupPlacement,
      popupPlacement = _props$popupPlacement === void 0 ? 'bottomLeft' : _props$popupPlacement,
      _props$direction = props.direction,
      direction = _props$direction === void 0 ? 'ltr' : _props$direction,
      onPopupVisibleChange = props.onPopupVisibleChange,
      _props$visible = props.visible,
      visible = _props$visible === void 0 ? false : _props$visible,
      _props$canEmpty = props.canEmpty,
      canEmpty = _props$canEmpty === void 0 ? true : _props$canEmpty,
      className = props.className,
      restProps = _objectWithoutProperties(props, _excluded);

  var initValues = (0, _react.useCallback)(function () {
    if (values instanceof Array) {
      var valuesLen = values.length;
      var startDate = values[0] || '';
      var endDate = values[valuesLen - 1] || '';
      return [startDate, endDate];
    }

    return [(0, _moment["default"])(), (0, _moment["default"])()];
  }, []);

  var _useState = (0, _react.useState)(visible),
      _useState2 = _slicedToArray(_useState, 2),
      popupVisible = _useState2[0],
      setPopupVisible = _useState2[1];

  var _useState3 = (0, _react.useState)(_utils.RangeSettingTypes.START),
      _useState4 = _slicedToArray(_useState3, 2),
      settingType = _useState4[0],
      setSettingType = _useState4[1];

  var _useState5 = (0, _react.useState)(initValues()),
      _useState6 = _slicedToArray(_useState5, 2),
      viewDate = _useState6[0],
      setViewDate = _useState6[1];

  var settingTypeRef = (0, _react.useRef)(_utils.RangeSettingTypes.START);

  var getPopupPlacement = function getPopupPlacement() {
    if (popupPlacement !== undefined) {
      return popupPlacement;
    }

    return direction === 'rtl' ? 'bottomRight' : 'bottomLeft';
  };

  var onChangeHandler = function onChangeHandler(date) {
    setViewDate(function (prevDate) {
      var nextDate = (0, _utils.setPickerDateBySettingType)({
        newDate: date[0],
        settingType: settingTypeRef.current,
        values: prevDate
      });
      var endDate = nextDate === null || nextDate === void 0 ? void 0 : nextDate[1];

      if ([_utils.RangeSettingTypes.START, _utils.RangeSettingTypes.RESET].includes( // @ts-ignore
      settingTypeRef.current) && !endDate) {
        setSettingType(_utils.RangeSettingTypes.END);
      } else if (settingTypeRef.current === _utils.RangeSettingTypes.END || !!endDate) {
        setSettingType(_utils.RangeSettingTypes.RESET);
      }

      return nextDate;
    });
    return true;
  };

  var onShortcutsDateChange = function onShortcutsDateChange(date) {
    setViewDate(date);
    setSettingType(_utils.RangeSettingTypes.RESET);
  };

  var onClearHandler = function onClearHandler() {
    setViewDate(['', '']);
    setSettingType(_utils.RangeSettingTypes.START);
  };

  var onConfirmHandler = function onConfirmHandler() {
    var newDate = viewDate.map(function (date) {
      return date ? (0, _moment["default"])(date).format(format) : date;
    });
    var result = onChange(newDate);

    if (result && result instanceof Promise) {
      result.then(function (res) {
        res && onClose();
      });
    } else if (result !== false) {
      onClose();
    }
  };

  var onClose = function onClose() {
    return setPopupVisible(false);
  };

  var onPopupVisibleChangeHandler = function onPopupVisibleChangeHandler(visible) {
    setPopupVisible(visible);
    onPopupVisibleChange === null || onPopupVisibleChange === void 0 ? void 0 : onPopupVisibleChange(visible);
  };

  var getPickerSettingType = function getPickerSettingType() {
    var _settingType = _utils.RangeSettingTypes.START;

    if (values instanceof Array) {
      var startDate = values[0] || '';
      var endDate = values[1] || '';

      if (!startDate) {
        _settingType = _utils.RangeSettingTypes.START;
      } else if (!endDate) {
        _settingType = _utils.RangeSettingTypes.END;
      } else {
        _settingType = _utils.RangeSettingTypes.RESET;
      }
    }

    setSettingType(_settingType);
  };

  (0, _react.useEffect)(function () {
    getPickerSettingType();
    setPopupVisible(visible);
  }, [visible]);
  (0, _react.useEffect)(function () {
    settingTypeRef.current = settingType;
  }, [settingType]);
  var popContent = (0, _react.useMemo)(function () {
    var okBtnDisabled = canEmpty ? viewDate.length === 1 || viewDate.filter(function (v) {
      return !v;
    }).length === 1 : viewDate.filter(function (v) {
      return !!v;
    }).length !== 2;
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])(_utils.PickerRangesClass, className)
    }, /*#__PURE__*/_react["default"].createElement(_placeholder["default"], {
      viewDate: viewDate,
      onChange: setViewDate,
      onFocus: setSettingType
    }), /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])("".concat(_utils.PickerRangesClass, "__main"))
    }, /*#__PURE__*/_react["default"].createElement(_shortcuts["default"], {
      onChange: onShortcutsDateChange
    }), /*#__PURE__*/_react["default"].createElement(_picker["default"], _extends({
      onChange: onChangeHandler,
      picker: picker,
      settingType: settingType,
      value: viewDate
    }, restProps, {
      displayMode: "tiled",
      multiple: true
    }))), /*#__PURE__*/_react["default"].createElement(_operations["default"], {
      disabled: okBtnDisabled,
      onCancel: onClose,
      onClear: onClearHandler,
      onOk: onConfirmHandler
    }));
  }, [canEmpty, settingType, viewDate]);
  return /*#__PURE__*/_react["default"].createElement(_context.RangePickerContext.Provider, {
    value: {
      values: values,
      picker: picker,
      format: format,
      settingType: settingType
    }
  }, /*#__PURE__*/_react["default"].createElement(_popup["default"], _extends({
    destroyPopupOnHide: true,
    extraClass: (0, _classnames["default"])(_utils.PickerDropdownClass),
    popup: popContent,
    popupVisible: popupVisible,
    popupPlacement: getPopupPlacement(),
    onPopupVisibleChange: onPopupVisibleChangeHandler
  }, restProps), /*#__PURE__*/_react["default"].createElement(_pickerTrigger["default"], _extends({
    focused: popupVisible,
    placeholder: (0, _getLocale.getLocale)('Rep_NewS_All'),
    viewDate: values
  }, restProps), children)));
};

var _default = RangePicker;
exports["default"] = _default;