"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 _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, _getDataSource$places, _getDataSource$places2, _getDataSource$places3, _getDataSource2;
  let {
      currency,
      id,
      locale,
      pricesLegend,
      rangeMaxDays = _Calendar.RANGE_MAX_DAYS,
      rangeMinDays,
      showPrices,
      text,
      top = false,
      unavailability: {
        disabledDates = [],
        minStayDates = {},
        minStayType
      } = {},
      onChange,
      onError,
      onSubmit,
      onValid
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    isMobile
  } = (0, _ui.useDevice)();
  const {
    translate
  } = (0, _locale.useLocale)();
  const _useStore = (0, _dataSources.useStore)(),
    {
      value: {
        skeleton = false
      }
    } = _useStore,
    store = _objectWithoutProperties(_useStore.value, _excluded2);
  const [focus, setFocus] = (0, _react.useState)();
  const [prices, setPrices] = (0, _react.useState)();
  const [value, setValue] = (0, _react.useState)((0, _helpers2.valueFormat)(others.value));
  const [visibleDate, setVisibleDate] = (0, _react.useState)();
  (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 [from, to] = value || [];
    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;
    setFocus(undefined);
    setValue((0, _helpers2.valueFormat)(next));
    onChange && onChange(next, event);
  };
  const handleNavigation = value => {
    setVisibleDate(value);
    return showPrices && id && getPrices(value);
  };
  const handleScroll = (_ref2, months) => {
    let {
      percentY
    } = _ref2;
    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;
  const [from, to] = (0, _helpers2.parseValue)(value);
  const props = _objectSpread(_objectSpread({}, others), {}, {
    locale,
    range: true,
    rangeMaxDays,
    rangeMinDays
  });
  const {
    config: {
      hotels: dataSource,
      lodgingDenomination: individual
    } = {}
  } = store || {};
  const tagId = (_getDataSource = (0, _helpers3.getDataSource)(store)) === null || _getDataSource === void 0 ? void 0 : (_getDataSource$places = _getDataSource.places) === null || _getDataSource$places === void 0 ? void 0 : (_getDataSource$places2 = _getDataSource$places.options) === null || _getDataSource$places2 === void 0 ? void 0 : (_getDataSource$places3 = _getDataSource$places2.find(function () {
    let {
      id: ids = [],
      isHotel
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return isHotel && ids[0] === id;
  })) === null || _getDataSource$places3 === void 0 ? void 0 : _getDataSource$places3.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