"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ratesResponse = void 0;
var _locale = require("@mirai/locale");
var _duetto = require("./duetto");
var _helpers = require("./helpers");
var _helpers2 = require("../../../../components/helpers");
var _helpers3 = require("../../../../components/Rates/helpers");
var _Core = require("../../../../Core.constants");
var _helpers4 = require("../../../../helpers");
var _helpers5 = require("../../helpers");
var _helpers6 = require("../helpers");
var _legacy = require("../helpers/legacy");
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); }
const ACCOMMODATION_TYPE_NAME = Object.keys(_Core.ACCOMMODATION_TYPE);
const ratesResponse = function () {
  var _variants$hotelId;
  let {
    device: {
      mobile
    } = {},
    response: {
      calendar: calendarSuggestion,
      currency,
      finder: {
        calendar = [],
        occupation = [],
        place: {
          title: searchCategory
        } = {},
        promocode = ''
      } = {},
      hotels,
      infantAge,
      language,
      session,
      tracking = {}
    } = {},
    store: {
      hotel: {
        accommodationType,
        features = {},
        variants = {}
      } = {},
      id,
      type,
      urlParams
    } = {}
  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  // ! -- TODO: Try to get all data from store -------------------------------------------------------------------------
  const {
    idchain,
    idoffers,
    idtokenprovider: hotelId,
    // ? TODO: Could we take it from store?
    roomTypeId
  } = (0, _helpers4.fetchUrlParams)(location.search);

  // ! -- TODO: use of tracking should be a temporary approach ---------------------------------------------------------
  const {
    country,
    hotelInfo: {
      currency: hotelCurrency = {},
      propertyName,
      propertyType
    } = {},
    hotelInfoBAR,
    localTaxesIncluded,
    rates,
    taxesIncluded,
    userCurrency: {
      value: userCurrencyValue
    } = {},
    userLocation = {}
  } = tracking;
  const {
    adults = 0,
    babies = 0,
    children = 0
  } = (0, _helpers2.getOccupationTotals)({
    infantAge,
    occupation
  });
  const {
    minRate,
    maxRate
  } = (0, _helpers6.getRatesPriceRange)(rates, hotelCurrency);
  const {
    days: nights
  } = (0, _locale.dateDiff)(...calendar);
  const {
    showPricePerNight = false
  } = (0, _helpers3.getFeatures)(features, urlParams);
  const has = {
    hotelAvailability: () => rates,
    chainAvailability: () => (hotelInfoBAR === null || hotelInfoBAR === void 0 ? void 0 : hotelInfoBAR.length) > 0 && hotelInfoBAR[0].bestAvailableRate,
    availability: () => has.hotelAvailability() || has.chainAvailability()
  };
  const step = hotels && !calendarSuggestion && searchCategory ? 'CHAINRESULT' : 'BOOKINGSTEP1';
  const common = _objectSpread(_objectSpread(_objectSpread({}, !has.availability() ? {
    availability: 'no'
  } : undefined), {}, {
    chainId: idchain,
    checkin: (0, _locale.dateFormat)(calendar[0], {
      format: 'DD/MM/YYYY'
    }),
    checkout: (0, _locale.dateFormat)(calendar[1], {
      format: 'DD/MM/YYYY'
    }),
    coupon: promocode,
    device: mobile ? 'MOBILE' : 'DESKTOP_TABLET',
    home: document.location.hostname,
    hotelId,
    idOffer: idoffers ? parseInt(idoffers) : undefined,
    idRoom: roomTypeId ? parseInt(roomTypeId) : undefined,
    language,
    lodgingDenomination: ACCOMMODATION_TYPE_NAME[((_variants$hotelId = variants[hotelId]) === null || _variants$hotelId === void 0 ? void 0 : _variants$hotelId.accommodationType) || accommodationType],
    multiroom: occupation.length > 1,
    numAdults: adults,
    numChildren: babies + children,
    numRooms: occupation.length,
    pricePerNight: showPricePerNight,
    propertyName,
    propertyType
  }, !rates && hotelInfoBAR ? {
    searchCategory
  } : undefined), {}, {
    step,
    userCountry: country,
    userLogged: !!session
  });
  const dataLayer = has.hotelAvailability() ? _objectSpread(_objectSpread({}, common), {}, {
    currency: hotelCurrency.code,
    exchangeRate: userCurrencyValue && hotelCurrency.value && userCurrencyValue / hotelCurrency.value,
    highestRate: (0, _helpers.parseRate)(maxRate, hotelCurrency, nights),
    localTaxesIncluded,
    lowestRate: (0, _helpers.parseRate)(minRate, hotelCurrency, nights),
    nights,
    ratesByRoom: Object.values(rates).map(function () {
      let {
        id,
        name,
        occupationOptions = {}
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return {
        id,
        name,
        occupations: Object.values(occupationOptions).map(function () {
          let {
            numAdults = 0,
            numFirstRangeChildren = 0,
            numSecondRangeChildren = 0,
            id,
            rates = {}
          } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
          return {
            adults: numAdults,
            children: numFirstRangeChildren + numSecondRangeChildren,
            id,
            rates: Object.values(rates).map(function () {
              let {
                boardOptions = {},
                id,
                name
              } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
              return {
                boards: Object.values(boardOptions).map(function () {
                  let {
                    id,
                    name,
                    totalBasePrice,
                    totalLocalTaxes = 0,
                    totalPriceWithTaxes
                  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
                  return {
                    id,
                    localTaxes: (0, _legacy.formatPrice)(totalLocalTaxes, hotelCurrency),
                    name,
                    netPrice: (0, _legacy.formatPrice)(totalBasePrice, hotelCurrency),
                    taxes: (0, _legacy.formatPrice)(totalPriceWithTaxes - totalBasePrice, hotelCurrency)
                  };
                }),
                id,
                name
              };
            })
          };
        })
      };
    }),
    taxesIncluded,
    userCurrency: currency,
    userLocation
  }) : has.chainAvailability() ? _objectSpread(_objectSpread({}, common), {}, {
    availability: 'yes',
    exchangeRate: userCurrencyValue && hotelInfoBAR[0].currency.value && userCurrencyValue / hotelInfoBAR[0].currency.value,
    hotelIds: hotelInfoBAR.map(function () {
      let {
        idTokenProvider
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return idTokenProvider;
    }).join(','),
    hotelNames: hotelInfoBAR.map(function () {
      let {
        hotelName
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return hotelName;
    }).join(','),
    lowestRate: (0, _legacy.formatPrice)(hotelInfoBAR[0].bestAvailableRate.totalPrice.internalWithTaxes / nights, hotelInfoBAR[0].currency),
    userLocation
  }) : _objectSpread(_objectSpread({}, common), {}, {
    cause: (hotelInfoBAR === null || hotelInfoBAR === void 0 ? void 0 : hotelInfoBAR.length) > 0 ? hotelInfoBAR[0].noAvailableReason : undefined
  });
  (0, _helpers5.dataLayerPush)((0, _helpers.getInitEvent)({
    mobile,
    hotel: {
      accommodationType,
      id: hotelId,
      variants
    },
    id,
    step,
    type
  }));
  (0, _helpers5.dataLayerPush)({
    event: has.availability() ? 'mirai.Availability' : 'mirai.noAvailability',
    'mirai.data': dataLayer
  });
  (0, _duetto.ratesResponse)(_objectSpread(_objectSpread({}, common), {}, {
    hotelCurrency,
    rates
  }));
  return dataLayer;
};
exports.ratesResponse = ratesResponse;
//# sourceMappingURL=ratesResponse.js.map