"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Calendar = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _Calendar = require("./Calendar.constants");
var _Calendar2 = require("./Calendar.l10n");
var style = _interopRequireWildcard(require("./Calendar.module.css"));
var _helpers = require("./helpers");
var _shared__ = require("../../../__shared__");
var _helpers2 = require("../../../helpers");
var _helpers3 = require("../../helpers");
const _excluded = ["currency", "id", "locale", "pricesLegend", "rangeMaxDays", "rangeMinDays", "showPrices", "text", "top", "unavailability", "onChange", "onError", "onSubmit", "onValid"],
  _excluded2 = ["skeleton"];
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, 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(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : 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(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
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(r) { if (Array.isArray(r)) return r; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
const Calendar = _ref => {
  var _getDataSource, _getDataSource2;
  let currency = _ref.currency,
    id = _ref.id,
    locale = _ref.locale,
    pricesLegend = _ref.pricesLegend,
    _ref$rangeMaxDays = _ref.rangeMaxDays,
    rangeMaxDays = _ref$rangeMaxDays === void 0 ? _Calendar.RANGE_MAX_DAYS : _ref$rangeMaxDays,
    rangeMinDays = _ref.rangeMinDays,
    showPrices = _ref.showPrices,
    text = _ref.text,
    _ref$top = _ref.top,
    top = _ref$top === void 0 ? false : _ref$top,
    _ref$unavailability = _ref.unavailability,
    _ref$unavailability2 = _ref$unavailability === void 0 ? {} : _ref$unavailability,
    _ref$unavailability2$ = _ref$unavailability2.disabledDates,
    disabledDates = _ref$unavailability2$ === void 0 ? [] : _ref$unavailability2$,
    _ref$unavailability2$2 = _ref$unavailability2.minStayDates,
    minStayDates = _ref$unavailability2$2 === void 0 ? {} : _ref$unavailability2$2,
    minStayType = _ref$unavailability2.minStayType,
    onChange = _ref.onChange,
    onError = _ref.onError,
    onSubmit = _ref.onSubmit,
    onValid = _ref.onValid,
    others = _objectWithoutProperties(_ref, _excluded);
  const _useDevice = (0, _ui.useDevice)(),
    isMobile = _useDevice.isMobile;
  const _useLocale = (0, _locale.useLocale)(),
    translate = _useLocale.translate;
  const deferCallback = (0, _helpers2.useDeferredCallback)();
  const _useStore = (0, _dataSources.useStore)(),
    _useStore$value = _useStore.value,
    _useStore$value$skele = _useStore$value.skeleton,
    skeleton = _useStore$value$skele === void 0 ? false : _useStore$value$skele,
    store = _objectWithoutProperties(_useStore$value, _excluded2);
  const _useState = (0, _react.useState)(),
    _useState2 = _slicedToArray(_useState, 2),
    focus = _useState2[0],
    setFocus = _useState2[1];
  const _useState3 = (0, _react.useState)(),
    _useState4 = _slicedToArray(_useState3, 2),
    prices = _useState4[0],
    setPrices = _useState4[1];
  const _useState5 = (0, _react.useState)((0, _helpers2.valueFormat)(others.value)),
    _useState6 = _slicedToArray(_useState5, 2),
    value = _useState6[0],
    setValue = _useState6[1];
  const _useState7 = (0, _react.useState)(),
    _useState8 = _slicedToArray(_useState7, 2),
    visibleDate = _useState8[0],
    setVisibleDate = _useState8[1];
  (0, _react.useEffect)(() => {
    if (skeleton) return;
    setPrices();
    const nextValue = visibleDate || (value === null || value === void 0 ? void 0 : value.length) && value[0] && (0, _helpers2.parseValue)(value)[0];
    currency && showPrices && id && getPrices(nextValue && (0, _locale.dateCalc)(nextValue, -1, 'months') || new Date(), _Calendar.MONTHS);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currency, id, showPrices]);
  (0, _react.useEffect)(() => {
    const _ref2 = value || [],
      _ref3 = _slicedToArray(_ref2, 2),
      from = _ref3[0],
      to = _ref3[1];
    if (onValid && from && to) onValid();else if (onError && (!from || !to)) onError(_Calendar.ERROR.NOT_FILLED);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value]);
  (0, _react.useEffect)(() => {
    setVisibleDate();
    JSON.stringify(value) !== JSON.stringify((0, _helpers2.valueFormat)(others.value)) && setValue((0, _helpers2.valueFormat)(others.value));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [others.value]);
  const getPrices = async function (from) {
    let rangeMonths = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
    if (_helpers2.IS_JEST || !from) return;
    const next = await (0, _helpers.fetchPrices)({
      currency,
      from,
      id,
      locale,
      rangeMonths
    });
    setPrices(current => {
      return {
        currency: next.currency,
        values: _objectSpread(_objectSpread({}, current === null || current === void 0 ? void 0 : current.values), next === null || next === void 0 ? void 0 : next.values)
      };
    });
  };
  const handleChange = function () {
    let next = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    let event = arguments.length > 1 ? arguments[1] : undefined;
    deferCallback(() => {
      setFocus(undefined);
      setValue((0, _helpers2.valueFormat)(next));
      onChange && onChange(next, event);
    });
  };
  const handleNavigation = nextValue => {
    deferCallback(() => {
      setVisibleDate(nextValue);
      showPrices && id && getPrices(nextValue);
    });
  };
  const handleScroll = (_ref4, months) => {
    let percentY = _ref4.percentY;
    const date = (0, _helpers.getVisibleDate)(percentY, months);
    setVisibleDate(date);
    return showPrices && id && getPrices(date, _Calendar.MONTHS);
  };
  const handleSubmit = event => onSubmit(value, event);
  const testId = others.testId;
  const _parseValue = (0, _helpers2.parseValue)(value),
    _parseValue2 = _slicedToArray(_parseValue, 2),
    from = _parseValue2[0],
    to = _parseValue2[1];
  const props = _objectSpread(_objectSpread({}, others), {}, {
    locale,
    range: true,
    rangeMaxDays,
    rangeMinDays
  });
  const _ref5 = store || {},
    _ref5$config = _ref5.config,
    _ref5$config2 = _ref5$config === void 0 ? {} : _ref5$config,
    dataSource = _ref5$config2.hotels,
    individual = _ref5$config2.lodgingDenomination;
  const tagId = (_getDataSource = (0, _helpers3.getDataSource)(store)) === null || _getDataSource === void 0 || (_getDataSource = _getDataSource.places) === null || _getDataSource === void 0 || (_getDataSource = _getDataSource.options) === null || _getDataSource === void 0 || (_getDataSource = _getDataSource.find(function () {
    let _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref6$id = _ref6.id,
      ids = _ref6$id === void 0 ? [] : _ref6$id,
      isHotel = _ref6.isHotel;
    return isHotel && ids[0] === id;
  })) === null || _getDataSource === void 0 ? void 0 : _getDataSource.value;
  const accommodationType = (0, _helpers2.getAccommodationType)({
    dataSource,
    hotels: (0, _helpers3.getHotels)((_getDataSource2 = (0, _helpers3.getDataSource)(store)) === null || _getDataSource2 === void 0 ? void 0 : _getDataSource2.placesSource, tagId),
    individual: individual && typeof individual === 'object' ? individual[id] : individual
  });
  return /*#__PURE__*/_react.default.createElement(_ui.View, {
    role: "calendar",
    className: (0, _ui.styles)(style.container, top && style.top)
  }, /*#__PURE__*/_react.default.createElement(_ui.Calendar, _extends({}, props, {
    captions: prices === null || prices === void 0 ? void 0 : prices.values,
    disabledDates: disabledDates,
    format: _helpers2.CALENDAR_FORMAT,
    l10n: {
      actionLoadMore: translate(_Calendar2.L10N.ACTION_LOAD_MORE_DATES),
      captionType: translate(_Calendar2.L10N.LABEL_PRICE)
    },
    months: isMobile ? _helpers2.MONTHS_IN_MOBILE : undefined,
    scrollEventThrottle: _Calendar.SCROLL_EVENT_MS,
    tooltips: (0, _helpers.calcTooltips)({
      from,
      minStayDates,
      minStayType,
      rangeMinDays,
      to,
      translate
    }),
    value: value,
    onChange: handleChange,
    onFocus: setFocus,
    onNavigation: handleNavigation,
    onScroll: handleScroll,
    className: (0, _ui.styles)(style.calendar, others.className)
  })), (prices === null || prices === void 0 ? void 0 : prices.currency) && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    inline: true,
    small: true,
    className: style.notification
  }, translate(_Calendar2.L10N.LABEL_INFO_PRICES, {
    accommodation: translate(_Calendar2.L10N.LABEL_ACCOMMODATION_TYPE, {
      type: accommodationType
    }),
    currency,
    guests: 2,
    nights: 1,
    taxType: pricesLegend
  })), onSubmit && /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: style.footer
  }, /*#__PURE__*/_react.default.createElement(_shared__.BookingDates, {
    from,
    focus,
    to,
    rangeMinDays
  }), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    testId: testId ? "".concat(testId, "-submit") : undefined,
    disabled: !from || !to,
    onPress: handleSubmit
  }, text || translate(_Calendar2.L10N.ACTION_SEARCH))));
};
exports.Calendar = Calendar;
Calendar.displayName = 'Mirai:Core:Finder:Calendar';
Calendar.propTypes = {
  currency: _propTypes.default.oneOf(_locale.CURRENCIES),
  id: _propTypes.default.string,
  locale: _propTypes.default.string,
  rangeMaxDays: _propTypes.default.number,
  rangeMinDays: _propTypes.default.number,
  showPrices: _propTypes.default.bool,
  pricesLegend: _propTypes.default.oneOf([_Calendar.TAX, _Calendar.TAX_FREE, _Calendar.TAX_PARTIAL]),
  text: _propTypes.default.string,
  top: _propTypes.default.bool,
  unavailability: _propTypes.default.shape({}),
  value: _propTypes.default.arrayOf(_propTypes.default.instanceOf(Date)),
  onChange: _propTypes.default.func,
  onError: _propTypes.default.func,
  onSubmit: _propTypes.default.func,
  onValid: _propTypes.default.func
};
//# sourceMappingURL=Calendar.js.map