"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); }
let fetchCall = 0;
const useRates = () => {
  const {
    isMobile,
    mobile
  } = (0, _ui.useDevice)();
  const {
    translate
  } = (0, _locale.useLocale)();
  const {
    set,
    value: {
      club = {},
      currency,
      finder = {},
      hotel = {},
      id,
      language,
      locale,
      rates: {
        cart: storeCart = [],
        meta
      } = {},
      occupation: {
        maxRooms
      } = {},
      urlParams,
      session,
      skeleton = false
    }
  } = (0, _dataSources.useStore)();
  const refRoomSelector = (0, _react.useRef)();
  const [cart, setCart] = (0, _react.useState)([]);
  const [clubDiscount, setClubDiscount] = (0, _react.useState)(club.discount);
  const [clubRate, setClubRate] = (0, _react.useState)(false);
  const [dataSource, setDataSource] = (0, _react.useState)();
  const [fetching, setFetching] = (0, _react.useState)(false);
  const [metaBoard, setMetaBoard] = (0, _react.useState)();
  const [responseError, setResponseError] = (0, _react.useState)();
  const [room, setRoom] = (0, _react.useState)();
  const [strictSearch, setStrictSearch] = (0, _react.useState)();
  const {
    calendar = [],
    occupation = [],
    place,
    promocode
  } = finder;
  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 {
          current: {
            offsetHeight = 0,
            offsetTop = 0
          } = {}
        } = refRoomSelector || {};
        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 => {
      if (clubRate) {
        setCart([]);
        setClubRate(false);
      }
      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
  }, [clubRate]);
  (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;
    !clubRate && 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, nextPromocode) => {
    const {
      notifications = []
    } = nextDataSource;
    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
        })
      });
      set({
        finder: {
          calendar,
          occupation,
          place,
          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)
      });
    }
    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)
      });
    }
    const {
      notification
    } = (0, _helpers.fetchUrlParams)(location.search) || {};
    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)
      });
    }
  };
  const fetch = async function () {
    let {
      nextRoom,
      nextOccupation = occupation,
      nextPlace = place,
      nextPromocode = finder.promocode
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    if (skeleton) return;
    const {
      id: [currentId] = []
    } = place || {};
    const {
      id: [nextId] = []
    } = nextPlace || {};
    let nextClubDiscount;
    if (nextPlace !== null && nextPlace !== void 0 && nextPlace.isHotel && currentId !== nextId) {
      const {
        variants = []
      } = club;
      const currentVariant = variants.find(function () {
        let {
          id = ''
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        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)({
        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 {
          roomId
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        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, 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,
      setClubRate,
      setDataSource,
      setMetaBoard,
      setRoom,
      setStrictSearch
    },
    device,
    multiRoom,
    fetch: debounceFetch,
    refRoomSelector,
    responseError,
    state: {
      cart,
      clubDiscount,
      clubRate,
      dataSource,
      fetching,
      metaBoard,
      room,
      strictSearch
    }
  };
};
exports.useRates = useRates;
//# sourceMappingURL=useRates.js.map