"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.consolidateStore = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _getAccommodationType = require("./getAccommodationType");
var _getClub = require("./getClub");
var _getCurrency = require("./getCurrency");
var _getLocale2 = require("./getLocale");
var _getMetaRates = require("./getMetaRates");
var _getPerformance = require("./getPerformance");
var _getTags = require("./getTags");
var _getVariant = require("./getVariant");
var _prepareRoom = require("./prepareRoom");
var _toOccupation = require("./toOccupation");
var _Core = require("../Core.constants");
const _excluded = ["el", "hotel", "id", "type"],
  _excluded2 = ["component"];
var _process;
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 IS_JEST = !!((_process = process) !== null && _process !== void 0 && (_process = _process.env) !== null && _process !== void 0 && _process.JEST_WORKER_ID);
const BOOKING = _Core.COMPONENTS.BOOKING,
  CHECKOUT = _Core.COMPONENTS.CHECKOUT,
  RATES = _Core.COMPONENTS.RATES;

/* eslint-disable no-unused-vars */
const consolidateStore = async function () {
  var _config$accomodation, _config$accomodation2, _config$accomodation3, _config$accomodation4, _config$accomodation5, _tags, _storageFinder$occupa, _promo, _config$languages;
  let _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
    _ref$components = _ref.components,
    components = _ref$components === void 0 ? [] : _ref$components,
    _ref$config = _ref.config,
    config = _ref$config === void 0 ? {} : _ref$config,
    _ref$cookies = _ref.cookies,
    cookies = _ref$cookies === void 0 ? {} : _ref$cookies,
    _ref$instance = _ref.instance,
    _ref$instance2 = _ref$instance === void 0 ? {} : _ref$instance,
    el = _ref$instance2.el,
    hotelId = _ref$instance2.hotel,
    id = _ref$instance2.id,
    type = _ref$instance2.type,
    instance = _objectWithoutProperties(_ref$instance2, _excluded),
    session = _ref.session,
    _ref$urlParams = _ref.urlParams,
    urlParams = _ref$urlParams === void 0 ? {} : _ref$urlParams;
  const miraiId = urlParams.miraiId;
  const isRates = components.some(function () {
    let _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      component = _ref2.component;
    return component === RATES;
  });
  const _ref3 = config.accomodation || {},
    _ref3$club = _ref3.club,
    club = _ref3$club === void 0 ? {} : _ref3$club,
    banner = _ref3.banner;

  // -- calendar -------------------------------------------------------------------------------------------------------
  const _ref4 = ((_config$accomodation = config.accomodation) === null || _config$accomodation === void 0 ? void 0 : _config$accomodation.calendar) || {},
    _ref4$maxDays = _ref4.maxDays,
    maxDays = _ref4$maxDays === void 0 ? 365 : _ref4$maxDays,
    _ref4$maxNights = _ref4.maxNights,
    rangeMaxDays = _ref4$maxNights === void 0 ? 31 : _ref4$maxNights,
    rangeMinDays = _ref4.nightsForDeal,
    _ref4$prices = _ref4.prices,
    showPrices = _ref4$prices === void 0 ? false : _ref4$prices,
    pricesLegend = _ref4.pricesWithTaxes;
  const calendar = {
    rangeMaxDays,
    rangeMinDays,
    pricesLegend: _Core.TAXES.includes(pricesLegend) ? pricesLegend : showPrices ? _Core.TAX_DEFAULT : undefined,
    showPrices,
    to: !IS_JEST ? (0, _locale.dateFormat)((0, _locale.dateCalc)(new Date(), maxDays, 'days'), {
      format: _Core.CALENDAR_FORMAT
    }) : undefined
  };

  // -- language, country & locale -------------------------------------------------------------------------------------
  const _getLocale = (0, _getLocale2.getLocale)(instance, urlParams),
    language = _getLocale.language,
    country = _getLocale.country,
    locale = _getLocale.locale;

  // -- currency -------------------------------------------------------------------------------------------------------
  const currency = await (0, _getCurrency.getCurrency)({
    id,
    instance,
    isRates,
    type,
    urlParams
  });

  // -- hotel ----------------------------------------------------------------------------------------------------------
  const hotel = {
    accommodationType: (0, _getAccommodationType.getAccommodationType)(config.lodgingDenomination, hotelId),
    features: ((_config$accomodation2 = config.accomodation) === null || _config$accomodation2 === void 0 ? void 0 : _config$accomodation2.features) || {},
    id: type === _Core.TYPE.CHAIN ? urlParams.idtokenprovider === id ? undefined : urlParams.idtokenprovider || urlParams.idHotel || hotelId : id,
    url: urlParams.home || window.location.origin,
    warningAvailability: config.minRoomsEngineNotification
  };
  if (type === _Core.TYPE.CHAIN) {
    const _config$hotels = config.hotels,
      hotels = _config$hotels === void 0 ? {} : _config$hotels;
    hotel.variants = {};
    Object.entries(hotels).map(_ref5 => {
      let _ref6 = _slicedToArray(_ref5, 2),
        key = _ref6[0],
        accommodationType = _ref6[1].lodgingDenomination;
      hotel.variants[key] = {
        accommodationType
      };
    });
  }

  // -- occupation -----------------------------------------------------------------------------------------------------
  const occupation = {
    dataSource: ((_config$accomodation3 = config.accomodation) === null || _config$accomodation3 === void 0 ? void 0 : _config$accomodation3.occupation) || [{
      type: _Core.TYPE.ADULT,
      min: 1,
      age: [18]
    }, {
      type: _Core.TYPE.CHILD,
      age: [0, 17],
      fulfill: true
    }],
    maxRooms: (_config$accomodation4 = config.accomodation) === null || _config$accomodation4 === void 0 || (_config$accomodation4 = _config$accomodation4.rooms) === null || _config$accomodation4 === void 0 ? void 0 : _config$accomodation4.maxOccupation,
    variants: ((_config$accomodation5 = config.accomodation) === null || _config$accomodation5 === void 0 ? void 0 : _config$accomodation5.variants) || []
  };

  // -- origin ---------------------------------------------------------------------------------------------------------
  const origin = {
    commissionCode: urlParams.hsri || _Core.TYPE_COMMISSION[type]
  };

  // -- tags -----------------------------------------------------------------------------------------------------------
  const chainSelector = config.chainSelector;
  let tags;
  if (type === _Core.TYPE.CHAIN && chainSelector) {
    const _chainSelector$placeH = chainSelector.placeHolder,
      placeHolder = _chainSelector$placeH === void 0 ? {} : _chainSelector$placeH,
      _chainSelector$trees = chainSelector.trees,
      trees = _chainSelector$trees === void 0 ? [] : _chainSelector$trees;
    tags = {
      options: (0, _getTags.getTags)(trees, language),
      placeholder: placeHolder[language]
    };
  }

  // -- finder ---------------------------------------------------------------------------------------------------------
  const storageFinder = !isRates ? new _dataSources.Storage({
    adapter: _dataSources.LocalAdapter
  }).get("".concat(_Core.FINDER_STORAGE_KEY, ":").concat(id)) || {} : {};
  let chainSelectorValue = urlParams.chainSelectorValue,
    checkin = urlParams.checkin,
    clientCode = urlParams.clientCode,
    _urlParams$nights = urlParams.nights,
    nights = _urlParams$nights === void 0 ? isRates ? 1 : 0 : _urlParams$nights,
    parties = urlParams.parties,
    promoCode = urlParams.promo;
  checkin = checkin ? (0, _locale.parseDate)(checkin) : isRates ? (0, _locale.UTC)(new Date()) : undefined;
  let checkout;
  if (checkin) checkout = (0, _locale.dateCalc)(checkin, parseInt(nights), 'days');
  let promo;
  if (config.showPromoNav) {
    const _config$accomodation6 = config.accomodation,
      _config$accomodation7 = _config$accomodation6 === void 0 ? {} : _config$accomodation6,
      _config$accomodation8 = _config$accomodation7.promo,
      configPromo = _config$accomodation8 === void 0 ? {} : _config$accomodation8,
      _config$promoText = config.promoText,
      placeholder = _config$promoText === void 0 ? {} : _config$promoText;
    promo = _objectSpread(_objectSpread({}, configPromo), {}, {
      placeholder,
      variants: Object.fromEntries(occupation.variants.map(function () {
        let _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          id = _ref7.id,
          _ref7$promo = _ref7.promo,
          _ref7$promo2 = _ref7$promo === void 0 ? {} : _ref7$promo,
          code = _ref7$promo2.code;
        return [id, code];
      }))
    });
  }
  let place;
  if (tags) {
    place = tags.options.find(function () {
      let _ref8 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref8$id = _ref8.id,
        _ref8$id2 = _ref8$id === void 0 ? [] : _ref8$id,
        _ref8$id3 = _slicedToArray(_ref8$id2, 1),
        idHotel = _ref8$id3[0],
        isHotel = _ref8.isHotel,
        value = _ref8.value;
      return chainSelectorValue && value === Number(chainSelectorValue) || isHotel && hotel.id === idHotel;
    });
    const _ref9 = place || {},
      _ref9$id = _ref9.id,
      _ref9$id2 = _ref9$id === void 0 ? [] : _ref9$id,
      _ref9$id3 = _slicedToArray(_ref9$id2, 1),
      id = _ref9$id3[0];
    const _ref0 = hotel.variants[id] || {},
      accommodationType = _ref0.accommodationType;
    if (accommodationType) hotel.accommodationType = accommodationType;
  }
  const finder = {
    place: place || storageFinder.place,
    calendar: checkin ? [checkin, checkout] : storageFinder.calendar && (0, _locale.dateDiff)(new Date(), new Date(storageFinder.calendar[0])).days > -1 ? [new Date(storageFinder.calendar[0]), new Date(storageFinder.calendar[1])] : [],
    occupation: parties ? (0, _toOccupation.toOccupation)({
      chainSelectorValue,
      occupation,
      parties,
      places: (_tags = tags) === null || _tags === void 0 ? void 0 : _tags.options
    }) : isRates ? [(0, _prepareRoom.prepareRoom)(occupation.dataSource)] : ((_storageFinder$occupa = storageFinder.occupation) === null || _storageFinder$occupa === void 0 ? void 0 : _storageFinder$occupa.map(rooms => rooms.map(function () {
      let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return _objectSpread(_objectSpread({}, value), value !== null && value !== void 0 && value.ages ? {
        ages: value.ages.map(age => age === null ? undefined : age)
      } : undefined);
    }))) || undefined,
    promocode: clientCode || promoCode || !isRates && ((_promo = promo) === null || _promo === void 0 ? void 0 : _promo.code) || storageFinder.promocode
  };

  // -- forwarder ------------------------------------------------------------------------------------------------------
  const host = "".concat(document.location.protocol, "//").concat(document.location.host);
  const isDevelopment = process.env.NODE_ENV === 'development' || window.IS_PLAYWRIGHT;
  const forwarder = {
    rates: miraiId ? "".concat(host, "/step1-rates") : "".concat(process.env.SERVICE_BOOKING, "/miraiFrontDispatcher.htm"),
    checkout: miraiId ? "".concat(host, "/step2-checkout") : "".concat(process.env.SERVICE_BOOKING, "/forwarder_client_form.htm"),
    booking: miraiId ? "".concat(host, "/step3-booking") : "".concat(process.env.SERVICE_BOOKING, "/forwarder_manage_reservation.htm"),
    signup: miraiId || isDevelopment ? "".concat(host, "/signup") : "".concat(process.env.SERVICE_USER, "/club/v1/forwarder/registration_process"),
    profile: miraiId || isDevelopment ? "".concat(host, "/profile") : "".concat(process.env.SERVICE_USER, "/club/v1/forwarder/members_area")
  };
  const _config$cookieBanner = config.cookieBanner,
    _config$cookieBanner2 = _config$cookieBanner === void 0 ? {} : _config$cookieBanner,
    active = _config$cookieBanner2.active,
    countryInactive = _config$cookieBanner2.countryInactive,
    showAll = _config$cookieBanner2.showAll;
  return _objectSpread(_objectSpread({
    banner: _objectSpread(_objectSpread({}, (club === null || club === void 0 ? void 0 : club.banner) || banner), {}, {
      isClub: !!(club !== null && club !== void 0 && club.banner),
      variants: Object.fromEntries(occupation.variants.map(function () {
        let _ref1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          id = _ref1.id,
          club = _ref1.club,
          banner = _ref1.banner;
        return [id, (club === null || club === void 0 ? void 0 : club.banner) || banner];
      }))
    }),
    config,
    cookies,
    cookieBanner: {
      active: active && (showAll || components.some(function () {
        let _ref10 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          component = _ref10.component;
        return [RATES, CHECKOUT, BOOKING].includes(component);
      })),
      countryInactive
    },
    urlParams
  }, instance), {}, {
    id,
    type,
    // region
    currency,
    language,
    country,
    locale,
    locales: (_config$languages = config.languages) === null || _config$languages === void 0 ? void 0 : _config$languages.map(language => language === 'no' ? 'nb' : language).map(language => "".concat(language, "-").concat(_locale.COUNTRIES[language])),
    // entities,
    calendar,
    club: (0, _getClub.getClub)({
      config,
      language,
      type,
      urlParams
    }),
    components: components.reduce((value, _ref11) => {
      let component = _ref11.component,
        props = _objectWithoutProperties(_ref11, _excluded2);
      value[component] = props;
      return value;
    }, {}),
    forwarder,
    hotel,
    occupation,
    origin,
    performance: (0, _getPerformance.getPerformance)(config, hotel.id),
    promo,
    session,
    tags,
    variant: (0, _getVariant.getVariant)({
      urlParams
    }) || _Core.VARIANT.A,
    // -- components
    checkout: !IS_JEST && urlParams.checkoutForm ? JSON.parse(urlParams.checkoutForm) : undefined,
    deals: undefined,
    finder,
    lisa: undefined,
    rates: {
      cart: urlParams.cart ? urlParams.cart.split(',') : urlParams.rates ? (0, _getMetaRates.getMetaRates)(urlParams.rates) : undefined,
      meta: !!urlParams.rates
    },
    rooms: undefined,
    signup: undefined
  });
};
exports.consolidateStore = consolidateStore;
//# sourceMappingURL=consolidateStore.js.map