"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useRates = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _services = require("@mirai/services");
var _ui = require("@mirai/ui");
var _react = require("react");
var _helpers = require("../../../helpers");
var _helpers2 = require("../../helpers");
var _helpers3 = require("../helpers");
var _Rates = require("../Rates.constants");
var _Rates2 = require("../Rates.l10n");
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; }
let fetchCall = 0;
const WARNING = 'warning';
const useRates = () => {
  const _useDevice = (0, _ui.useDevice)(),
    isMobile = _useDevice.isMobile,
    mobile = _useDevice.mobile;
  const _useLocale = (0, _locale.useLocale)(),
    translate = _useLocale.translate;
  const _useStore = (0, _dataSources.useStore)(),
    set = _useStore.set,
    _useStore$value = _useStore.value,
    _useStore$value$club = _useStore$value.club,
    club = _useStore$value$club === void 0 ? {} : _useStore$value$club,
    currency = _useStore$value.currency,
    _useStore$value$finde = _useStore$value.finder,
    finder = _useStore$value$finde === void 0 ? {} : _useStore$value$finde,
    _useStore$value$hotel = _useStore$value.hotel,
    hotel = _useStore$value$hotel === void 0 ? {} : _useStore$value$hotel,
    id = _useStore$value.id,
    language = _useStore$value.language,
    locale = _useStore$value.locale,
    _useStore$value$rates = _useStore$value.rates,
    _useStore$value$rates2 = _useStore$value$rates === void 0 ? {} : _useStore$value$rates,
    _useStore$value$rates3 = _useStore$value$rates2.cart,
    storeCart = _useStore$value$rates3 === void 0 ? [] : _useStore$value$rates3,
    meta = _useStore$value$rates2.meta,
    _useStore$value$occup = _useStore$value.occupation,
    _useStore$value$occup2 = _useStore$value$occup === void 0 ? {} : _useStore$value$occup,
    maxRooms = _useStore$value$occup2.maxRooms,
    urlParams = _useStore$value.urlParams,
    session = _useStore$value.session,
    _useStore$value$skele = _useStore$value.skeleton,
    skeleton = _useStore$value$skele === void 0 ? false : _useStore$value$skele;
  const refRoomSelector = (0, _react.useRef)();
  const _useState = (0, _react.useState)([]),
    _useState2 = _slicedToArray(_useState, 2),
    cart = _useState2[0],
    setCart = _useState2[1];
  const _useState3 = (0, _react.useState)(club.discount),
    _useState4 = _slicedToArray(_useState3, 2),
    clubDiscount = _useState4[0],
    setClubDiscount = _useState4[1];
  const _useState5 = (0, _react.useState)(),
    _useState6 = _slicedToArray(_useState5, 2),
    dataSource = _useState6[0],
    setDataSource = _useState6[1];
  const _useState7 = (0, _react.useState)(false),
    _useState8 = _slicedToArray(_useState7, 2),
    fetching = _useState8[0],
    setFetching = _useState8[1];
  const _useState9 = (0, _react.useState)(),
    _useState0 = _slicedToArray(_useState9, 2),
    metaBoard = _useState0[0],
    setMetaBoard = _useState0[1];
  const _useState1 = (0, _react.useState)(),
    _useState10 = _slicedToArray(_useState1, 2),
    responseError = _useState10[0],
    setResponseError = _useState10[1];
  const _useState11 = (0, _react.useState)(),
    _useState12 = _slicedToArray(_useState11, 2),
    room = _useState12[0],
    setRoom = _useState12[1];
  const _useState13 = (0, _react.useState)(),
    _useState14 = _slicedToArray(_useState13, 2),
    strictSearch = _useState14[0],
    setStrictSearch = _useState14[1];
  const _finder$calendar = finder.calendar,
    calendar = _finder$calendar === void 0 ? [] : _finder$calendar,
    _finder$occupation = finder.occupation,
    occupation = _finder$occupation === void 0 ? [] : _finder$occupation,
    place = finder.place,
    promocode = finder.promocode;
  const device = mobile ? 'MOBILE' : 'DESKTOP_TABLET';
  const multiRoom = (occupation === null || occupation === void 0 ? void 0 : occupation.length) > 1;

  // eslint-disable-next-line react-hooks/exhaustive-deps
  (0, _react.useEffect)(() => {
    skeleton && setFetching(true);
  }, [skeleton]);
  (0, _react.useEffect)(() => {
    if (multiRoom) {
      if (room > 0) {
        const _ref = refRoomSelector || {},
          _ref$current = _ref.current,
          _ref$current2 = _ref$current === void 0 ? {} : _ref$current,
          _ref$current2$offsetH = _ref$current2.offsetHeight,
          offsetHeight = _ref$current2$offsetH === void 0 ? 0 : _ref$current2$offsetH,
          _ref$current2$offsetT = _ref$current2.offsetTop,
          offsetTop = _ref$current2$offsetT === void 0 ? 0 : _ref$current2$offsetT;
        window.scrollTo({
          top: offsetTop + (isMobile ? offsetHeight : 0),
          behavior: 'smooth'
        });
      }
      setDataSource();
    }
    (room !== undefined || multiRoom) && debounceFetch({
      nextRoom: room
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [room]);
  (0, _react.useEffect)(() => {
    const callback = async next => {
      setMetaBoard();
      setClubDiscount(typeof next !== 'object' ? next : undefined);
    };
    _dataSources.Event.subscribe(_helpers2.EVENT.RATES_FILTER_CLUB, callback);
    return () => _dataSources.Event.unsubscribe(_helpers2.EVENT.RATES_FILTER_CLUB, callback);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _react.useEffect)(() => {
    if (!dataSource && (!responseError || !responseError.tracking) || room) return;
    _dataSources.Event.publish(_helpers2.EVENT.RATES_RESPONSE, {
      error: !!responseError,
      event: _helpers2.EVENT.RATES_RESPONSE,
      response: _objectSpread(_objectSpread({}, dataSource || responseError), {}, {
        currency,
        finder: {
          calendar,
          occupation,
          place,
          promocode
        },
        language,
        session
      })
    });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSource, responseError]);
  (0, _react.useEffect)(() => {
    if (!dataSource || !storeCart.length) return;
    (0, _helpers3.getBoard)({
      cart,
      dataSource,
      storeCart
    }).then(board => {
      if (meta) {
        _dataSources.Event.publish(_helpers2.EVENT.NOTIFICATION, {
          contrast: true,
          defaultMessage: translate(_Rates2.L10N.NOTIFICATION_META_RATE_FOUND, {
            utm_source: _Rates.UTM_SOURCE_NAME[urlParams.utm_source] || urlParams.utm_source
          })
        });
      }
      setMetaBoard(board);
      set({
        rates: undefined
      });
    }).catch(() => {
      set({
        rates: undefined
      });
    });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSource]);
  (0, _react.useEffect)(() => {
    if (!clubDiscount && !currency && !session && strictSearch === undefined) return;
    setCart([]);
    setRoom(undefined);
    debounceFetch();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [clubDiscount, currency, session, strictSearch]);
  (0, _react.useEffect)(() => {
    if (!locale) return;
    debounceFetch({
      nextRoom: room
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [locale]);
  const checkNotifications = (nextDataSource, nextCalendar, nextOccupation, nextPlace, nextPromocode) => {
    const _nextDataSource$notif = nextDataSource.notifications,
      notifications = _nextDataSource$notif === void 0 ? [] : _nextDataSource$notif;
    const trackNotification = (notificationType, notificationMessage) => {
      _dataSources.Event.publish(_helpers2.EVENT.METRICS, {
        id: _helpers2.METRICS_EVENTS.RATES_INTERACTION,
        action: 'notification_show',
        notification_type: notificationType,
        notification_message: notificationMessage
      });
    };
    if (notifications.includes(_Rates.NOTIFICATION.PROMOCODE_NOT_FOUND) && nextPromocode) {
      _dataSources.Event.publish(_helpers2.EVENT.NOTIFICATION, {
        contrast: true,
        defaultMessage: translate(_Rates2.L10N.NOTIFICATION_PROMOCODE_NOT_FOUND, {
          promocode: nextPromocode
        })
      });
      trackNotification(WARNING, 'promo_code_unavailable');
      set({
        finder: {
          calendar: nextCalendar,
          occupation: nextOccupation,
          place: nextPlace,
          promocode: ''
        }
      });
      _dataSources.Event.publish(_helpers2.EVENT.RATES_FILTER_PROMOCODE, {
        promocode: undefined
      });
    } else if (nextPromocode !== finder.promocode) {
      _dataSources.Event.publish(_helpers2.EVENT.RATES_FILTER_PROMOCODE, {
        promocode: nextPromocode
      });
    }
    if (notifications.includes(_Rates.NOTIFICATION.ROOM_NOT_FOUNT) && urlParams.roomTypeId) {
      _dataSources.Event.publish(_helpers2.EVENT.NOTIFICATION, {
        contrast: true,
        defaultMessage: translate(_Rates2.L10N.NOTIFICATION_ROOM_NOT_FOUND)
      });
      trackNotification(WARNING, 'room_unavailable');
    }
    if (notifications.includes(_Rates.NOTIFICATION.OFFER_NOT_FOUND) && urlParams.idoffers) {
      _dataSources.Event.publish(_helpers2.EVENT.NOTIFICATION, {
        contrast: true,
        defaultMessage: translate(_Rates2.L10N.NOTIFICATION_OFFER_NOT_FOUND)
      });
      trackNotification(WARNING, 'offer_unavailable');
    }
    const _ref2 = (0, _helpers.fetchUrlParams)(location.search) || {},
      notification = _ref2.notification;
    const validateError = notification && _Rates2.L10N.NOTIFICATION_VALIDATE[notification];
    if (validateError) {
      (0, _helpers2.replaceUrlParams)({
        notification: undefined
      });
      _dataSources.Event.publish(_helpers2.EVENT.NOTIFICATION, {
        warning: true,
        defaultMessage: translate(validateError)
      });
      trackNotification(WARNING, 'rate_validation_error');
    }
  };
  const fetch = async function () {
    let _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref3$nextCalendar = _ref3.nextCalendar,
      nextCalendar = _ref3$nextCalendar === void 0 ? calendar : _ref3$nextCalendar,
      nextRoom = _ref3.nextRoom,
      _ref3$nextOccupation = _ref3.nextOccupation,
      nextOccupation = _ref3$nextOccupation === void 0 ? occupation : _ref3$nextOccupation,
      _ref3$nextPlace = _ref3.nextPlace,
      nextPlace = _ref3$nextPlace === void 0 ? place : _ref3$nextPlace,
      _ref3$nextPromocode = _ref3.nextPromocode,
      nextPromocode = _ref3$nextPromocode === void 0 ? finder.promocode : _ref3$nextPromocode;
    if (skeleton) return;
    const _ref4 = place || {},
      _ref4$id = _ref4.id,
      _ref4$id2 = _ref4$id === void 0 ? [] : _ref4$id,
      _ref4$id3 = _slicedToArray(_ref4$id2, 1),
      currentId = _ref4$id3[0];
    const _ref5 = nextPlace || {},
      _ref5$id = _ref5.id,
      _ref5$id2 = _ref5$id === void 0 ? [] : _ref5$id,
      _ref5$id3 = _slicedToArray(_ref5$id2, 1),
      nextId = _ref5$id3[0];
    let nextClubDiscount;
    if (nextPlace !== null && nextPlace !== void 0 && nextPlace.isHotel && currentId !== nextId) {
      const _club$variants = club.variants,
        variants = _club$variants === void 0 ? [] : _club$variants;
      const currentVariant = variants.find(function () {
        let _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref6$id = _ref6.id,
          id = _ref6$id === void 0 ? '' : _ref6$id;
        return id.toString() === nextId.toString();
      });
      nextClubDiscount = currentVariant === null || currentVariant === void 0 ? void 0 : currentVariant.discount;
      if (currentVariant && nextClubDiscount !== clubDiscount) {
        _dataSources.Event.publish(_helpers2.EVENT.RATES_FILTER_CLUB, nextClubDiscount);
        return;
      }
    }
    _dataSources.Event.publish(_helpers2.EVENT.FINDER, {
      calendar: undefined
    });
    setFetching(true);
    setResponseError();
    let urlParams = (0, _helpers.fetchUrlParams)(location.search);
    if (!urlParams.checkin || !urlParams.nights || !urlParams.parties) {
      urlParams = _objectSpread(_objectSpread({}, urlParams), (0, _helpers3.getFinderParams)(_objectSpread(_objectSpread({}, finder), {}, {
        hotel
      })));
      (0, _helpers2.replaceUrlParams)(urlParams);
    }
    if (nextPlace && !nextPlace.isHotel) {
      (0, _helpers2.replaceUrlParams)(_objectSpread(_objectSpread({}, urlParams), {}, {
        idtokenprovider: undefined
      }));
    }
    const params = _objectSpread(_objectSpread(_objectSpread({
      currency
    }, urlParams), club.active ? {
      club,
      clubDiscount
    } : undefined), {}, {
      id,
      locale,
      maxRooms,
      device,
      occupation: nextOccupation,
      place,
      selectedIds: cart.map(function () {
        let _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          roomId = _ref7.roomId;
        return roomId;
      }).join(','),
      session,
      strictSearch
    });
    if (nextRoom !== undefined) params.parties = (0, _helpers2.parseToParties)([nextOccupation[nextRoom || 0]]);
    const lastFetchCall = ++fetchCall;
    const nextDataSource = await _services.ServiceRates.get(params).catch(setResponseError);
    if (lastFetchCall !== fetchCall) return;
    if (nextDataSource !== null && nextDataSource !== void 0 && nextDataSource.externalSignout) return (0, _helpers3.signout)({
      club,
      language
    });
    if (nextDataSource && nextRoom === undefined) {
      checkNotifications(nextDataSource, nextCalendar, nextOccupation, nextPlace, nextPromocode);
      if ((nextOccupation === null || nextOccupation === void 0 ? void 0 : nextOccupation.length) > 1 && nextRoom === undefined) setRoom(0);
    }
    setDataSource(nextDataSource);
    setFetching(false);
  };
  const debounceFetch = (0, _helpers.debounce)(fetch, 60);
  return {
    actions: {
      setCart,
      setDataSource,
      setMetaBoard,
      setRoom,
      setStrictSearch
    },
    device,
    multiRoom,
    fetch: debounceFetch,
    refRoomSelector,
    responseError,
    state: {
      cart,
      clubDiscount,
      dataSource,
      fetching,
      metaBoard,
      room,
      strictSearch
    }
  };
};
exports.useRates = useRates;
//# sourceMappingURL=useRates.js.map