"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 _getLocale = 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, _process$env;
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 IS_JEST = !!((_process = process) !== null && _process !== void 0 && (_process$env = _process.env) !== null && _process$env !== void 0 && _process$env.JEST_WORKER_ID);
const {
  BOOKING,
  CHECKOUT,
  RATES
} = _Core.COMPONENTS;

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

  // -- calendar -------------------------------------------------------------------------------------------------------
  const {
    maxDays = 365,
    maxNights: rangeMaxDays = 31,
    nightsForDeal: rangeMinDays,
    prices: showPrices = false,
    pricesWithTaxes: pricesLegend
  } = ((_config$accomodation = config.accomodation) === null || _config$accomodation === void 0 ? void 0 : _config$accomodation.calendar) || {};
  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 {
    language,
    country,
    locale
  } = (0, _getLocale.getLocale)(instance, urlParams);

  // -- 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 {
      hotels = {}
    } = config;
    hotel.variants = {};
    Object.entries(hotels).map(_ref2 => {
      let [key, {
        lodgingDenomination: accommodationType
      }] = _ref2;
      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 ? void 0 : (_config$accomodation5 = _config$accomodation4.rooms) === null || _config$accomodation5 === void 0 ? void 0 : _config$accomodation5.maxOccupation,
    variants: ((_config$accomodation6 = config.accomodation) === null || _config$accomodation6 === void 0 ? void 0 : _config$accomodation6.variants) || []
  };

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

  // -- tags -----------------------------------------------------------------------------------------------------------
  const {
    chainSelector
  } = config;
  let tags;
  if (type === _Core.TYPE.CHAIN && chainSelector) {
    const {
      placeHolder = {},
      trees = []
    } = chainSelector;
    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,
    checkin,
    clientCode,
    nights = isRates ? 1 : 0,
    parties,
    promo: promoCode
  } = urlParams;
  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 {
      accomodation: {
        promo: configPromo = {}
      } = {},
      promoText: placeholder = {}
    } = config;
    promo = _objectSpread(_objectSpread({}, configPromo), {}, {
      placeholder,
      variants: Object.fromEntries(occupation.variants.map(function () {
        let {
          id,
          promo: {
            code
          } = {}
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        return [id, code];
      }))
    });
  }
  let place;
  if (tags) {
    place = tags.options.find(function () {
      let {
        id: [idHotel] = [],
        isHotel,
        value
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return chainSelectorValue && value === Number(chainSelectorValue) || isHotel && hotel.id === idHotel;
    });
    const {
      id: [id] = []
    } = place || {};
    const {
      accommodationType
    } = hotel.variants[id] || {};
    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 {
    cookieBanner: {
      active,
      countryInactive,
      showAll
    } = {}
  } = config;
  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 {
          id,
          club,
          banner
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        return [id, (club === null || club === void 0 ? void 0 : club.banner) || banner];
      }))
    }),
    config,
    cookies,
    cookieBanner: {
      active: active && (showAll || components.some(function () {
        let {
          component
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        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, _ref3) => {
      let {
          component
        } = _ref3,
        props = _objectWithoutProperties(_ref3, _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
    }),
    // -- 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