"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RatesExplorer = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _services = require("@mirai/services");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _helpers = require("./helpers");
var _RatesExplorer = require("./RatesExplorer.Calendar");
var _RatesExplorer2 = require("./RatesExplorer.constants");
var _RatesExplorer3 = require("./RatesExplorer.l10n");
var style = _interopRequireWildcard(require("./RatesExplorer.module.css"));
var _RatesExplorer4 = _interopRequireDefault(require("./RatesExplorer.skeleton"));
var _ = require("../");
var _Core = require("../../../Core.constants");
var _prepareRoom = require("../../../helpers/prepareRoom");
var _helpers2 = require("../../helpers");
var _toParties = require("../Occupation/helpers/toParties");
const _excluded = ["offerId", "roomId"],
  _excluded2 = ["cookies", "currency", "deals", "hotel", "language", "locale", "origin", "rooms", "skeleton", "urlParams"];
/* eslint-disable react-hooks/exhaustive-deps */
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 RatesExplorer = _ref => {
  let {
      offerId,
      roomId
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    isMobile
  } = (0, _ui.useDevice)();
  const {
    translate
  } = (0, _locale.useLocale)();
  const _useStore = (0, _dataSources.useStore)(),
    {
      set,
      value: {
        cookies = {},
        currency,
        deals,
        hotel,
        language,
        locale,
        origin,
        rooms,
        skeleton = false,
        urlParams = {}
      }
    } = _useStore,
    store = _objectWithoutProperties(_useStore.value, _excluded2);
  const ref = (0, _react.useRef)(null);
  const [busy, setBusy] = (0, _react.useState)(false);
  const [dataSource, setDataSource] = (0, _react.useState)();
  const [error, setError] = (0, _react.useState)({});
  const [visible, setVisible] = (0, _react.useState)();
  const [visited, setVisited] = (0, _react.useState)({});
  const [notification, setNotification] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    !isMobile && document.addEventListener('click', handleClickOutside, true);
    window.addEventListener('pageshow', handlePageShow);
    return () => {
      !isMobile && document.removeEventListener('click', handleClickOutside, true);
      window.removeEventListener('pageshow', handlePageShow);
    };
  }, []);
  (0, _react.useEffect)(() => {
    if (skeleton) return;
    (async () => setDataSource(await getDataSource()))();
  }, [currency, locale]);
  (0, _react.useEffect)(() => {
    const {
      calendar: {
        pricesInfo: {
          guests
        } = {}
      } = {},
      occupation: {
        minRooms = 1,
        dataSource: occupation = []
      } = {}
    } = dataSource || {};
    !(value !== null && value !== void 0 && value.occupation) && occupation.length > 0 && handleChange('occupation', [...Array(minRooms)].map(() => Array.isArray(guests) ? guests.map(guest => _objectSpread(_objectSpread({}, guest), {}, {
      ages: new Array(guest.amount).fill(undefined)
    })) : (0, _prepareRoom.prepareRoom)(occupation)));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSource]);
  (0, _react.useEffect)(() => {
    visible && setVisited(_objectSpread(_objectSpread({}, visited), {}, {
      ["".concat(visible)]: true
    }));
  }, [visible]);
  const handleChange = (field, fieldValue) => {
    if (!dataSource) return;
    const nextValue = _objectSpread(_objectSpread({}, value), {}, {
      [field]: fieldValue
    });
    set(offerId ? {
      deals: nextValue
    } : {
      rooms: nextValue
    });
  };
  const handleClear = () => {
    set(offerId ? {
      deals: undefined
    } : {
      rooms: undefined
    });
    setError({});
    setVisible();
    setVisited(false);
    setNotification();
  };
  const handleClickOutside = function () {
    var _ref$current;
    let {
      target
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return !((_ref$current = ref.current) !== null && _ref$current !== void 0 && _ref$current.contains(target)) && target.type !== 'text' && setVisible();
  };
  const handlePageShow = async function () {
    let {
      persisted
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    if (!persisted) return;
    setBusy(false);
    handleClear();
    setDataSource(await getDataSource());
  };
  const handleSubmit = () => {
    setNotification();
    const calendarValid = (0, _helpers.validate)({
      dataSource,
      value
    });
    if (!calendarValid) {
      isMobile ? setVisible(_RatesExplorer2.FIELD.CALENDAR) : setNotification(true);
      return;
    }
    if (error.occupation) {
      setVisible(_RatesExplorer2.FIELD.OCCUPATION);
      return;
    }
    setBusy(true);
    const {
      calendar,
      occupation,
      promoCode
    } = value;
    const params = _objectSpread(_objectSpread({
      checkin: (0, _locale.dateFormat)(calendar[0], {
        format: 'DD/MM/YYYY'
      }),
      clientCode: promoCode || '',
      currency: (0, _helpers.getCurrency)({
        urlParams,
        cookies,
        currency
      }) || '',
      hsri: origin.commissionCode
    }, offerId ? {
      idoffers: offerId
    } : undefined), {}, {
      idtokenprovider: hotel.id,
      lang: language,
      nights: (0, _locale.dateDiff)(calendar[0], calendar[1]).days,
      parties: window.btoa(JSON.stringify((0, _toParties.toParties)(occupation)))
    }, roomId ? {
      roomTypeId: roomId
    } : undefined);
    window.location.href = "".concat(process.env.SERVICE_BOOKING, "/").concat(_Core.REDIRECT_PATH).concat((0, _helpers2.toQueryString)(params));
    setBusy(true);
  };
  const getDataSource = () => (offerId ? _services.ServiceDeals : _services.ServiceRooms).get(_objectSpread(_objectSpread({}, store), {}, {
    currency: (0, _helpers.getCurrency)({
      cookies,
      currency,
      urlParams
    }),
    hotel,
    locale,
    offerId,
    roomId
  })).catch(() => {});
  const value = deals || rooms || {};
  const {
    calendar = [],
    occupation,
    promoCode = ''
  } = value;
  const role = offerId ? 'deals' : 'rooms';
  return !skeleton ? /*#__PURE__*/_react.default.createElement(_ui.View, _extends({}, others, {
    role: role,
    className: (0, _ui.styles)(style.ratesExplorer, others.className)
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: style.header
  }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true,
    headline: true,
    level: 2,
    markdown: false,
    className: style.text
  }, translate(_RatesExplorer3.L10N.LABEL_SELECT_DATES_PERSONS)), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    transparent: true,
    onPress: handleClear,
    testId: "".concat(role, "-button-clear")
  }, /*#__PURE__*/_react.default.createElement(_ui.Icon, {
    value: _helpers2.ICON.CLEAR
  }), translate(_RatesExplorer3.L10N.ACTION_CLEAR))), /*#__PURE__*/_react.default.createElement(_RatesExplorer.Calendar, _extends({}, dataSource === null || dataSource === void 0 ? void 0 : dataSource.calendar, {
    value: calendar,
    visible: visible === _RatesExplorer2.FIELD.CALENDAR,
    visited: visited.calendar,
    onChange: (calendar, event) => handleChange('calendar', calendar, event),
    onPress: () => setVisible(visible !== _RatesExplorer2.FIELD.CALENDAR ? _RatesExplorer2.FIELD.CALENDAR : undefined),
    testId: "".concat(role, "-calendar")
  })), /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.container
  }, !isMobile && notification && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: true,
    small: true,
    wide: true,
    className: style.notification
  }, translate(_RatesExplorer3.L10N.NOTIFICATION_SELECT_DATES)), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: !isMobile,
    className: style.extras
  }, /*#__PURE__*/_react.default.createElement(_.FieldOccupation, _extends({}, dataSource === null || dataSource === void 0 ? void 0 : dataSource.occupation, {
    error: !!error.occupation,
    forceRender: true,
    hideLabel: !isMobile,
    hotels: [hotel === null || hotel === void 0 ? void 0 : hotel.id],
    ref: ref,
    text: translate(_RatesExplorer3.L10N.ACTION_APPLY),
    value: occupation,
    visible: visible === _RatesExplorer2.FIELD.OCCUPATION,
    onChange: occupation => handleChange('occupation', occupation),
    onError: occupation => setError(_objectSpread(_objectSpread({}, error), {}, {
      occupation
    })),
    onPress: () => setVisible(visible !== _RatesExplorer2.FIELD.OCCUPATION ? _RatesExplorer2.FIELD.OCCUPATION : undefined),
    onSubmit: isMobile ? () => setVisible() : undefined,
    onValid: () => setError(_objectSpread(_objectSpread({}, error), {}, {
      occupation: undefined
    })),
    testId: "".concat(role, "-occupation")
  })), /*#__PURE__*/_react.default.createElement(_.FieldPromocode, {
    value: promoCode,
    visible: visible === _RatesExplorer2.FIELD.PROMOCODE,
    onChange: promoCode => handleChange('promoCode', promoCode),
    onEnter: () => setVisible(_RatesExplorer2.FIELD.PROMOCODE),
    onLeave: () => setVisible(undefined),
    testId: "".concat(role, "-promocode")
  }), !isMobile && /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.footer
  }), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    busy: busy,
    large: true,
    wide: isMobile,
    onPress: handleSubmit,
    className: style.cta,
    testId: "".concat(role, "-button")
  }, translate(_RatesExplorer3.L10N.ACTION_SEARCH))))) : /*#__PURE__*/_react.default.createElement(_RatesExplorer4.default, null);
};
exports.RatesExplorer = RatesExplorer;
RatesExplorer.displayName = 'Mirai:Core:RatesExplorer';
RatesExplorer.propTypes = {
  offerId: _propTypes.default.string,
  roomId: _propTypes.default.string
};
//# sourceMappingURL=RatesExplorer.js.map