"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.showProductVariantsForItem = exports["default"] = exports.createPricePropsFromState = exports.createBulkNameErrors = exports.createAmountPropsFromState = void 0;
var _get = _interopRequireDefault(require("lodash/get"));
var _isArray = _interopRequireDefault(require("lodash/isArray"));
var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));
var _upperFirst = _interopRequireDefault(require("lodash/upperFirst"));
var _uniqBy = _interopRequireDefault(require("lodash/uniqBy"));
var _ComponentContainer = require("../../../../Framework/ComponentContainer");
var _i18n = require("../../../../Framework/i18n");
var _ServiceLocator = require("../../../ServiceLocator");
var _createSelector = _interopRequireDefault(require("../../../../Utils/Function/createSelector"));
var _Selectors = require("../../../Reducers/Configurator/Selectors");
var _Selectors2 = require("../../../Reducers/UI/Selectors");
var _configuration = require("../../../configuration");
var _Selectors3 = require("../../../Reducers/DesignArea/Selectors");
var _AmountPrice = _interopRequireDefault(require("../../Components/AmountPrice"));
var _AmountPriceAdminareaWrapper = require("./AmountPriceAdminareaWrapper");
var _Selectors4 = require("../../../Reducers/ConfigurationMode/Selectors");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
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 _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
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; }
var showProductVariantsForItem = exports.showProductVariantsForItem = (0, _createSelector["default"])(_Selectors.getItem, function (item) {
  return (0, _Selectors.findMaxChildrenCount)(item) > 1;
});
var createAmountPropsFromState = exports.createAmountPropsFromState = (0, _createSelector["default"])(_Selectors.getItem, _Selectors.getSelectedAmounts, _Selectors.getClient, _Selectors.getBulkNames, function (item, selectedAmounts, client) {
  var query = new URLSearchParams(location.search);
  var props = {
    title: item && item.title,
    amount: 0,
    hidePrices: query.has('_hide_prices') ? query.get('_hide_prices') === '1' : client && !!client.hidePrices
  };
  if ((0, _isPlainObject["default"])(selectedAmounts)) {
    props.amount = Object.values(selectedAmounts).reduce(function (sum, amount) {
      return sum + amount;
    }, 0);
  }
  return props;
});
var createBulkNameErrors = exports.createBulkNameErrors = (0, _createSelector["default"])(_Selectors.getItem, _Selectors.getSelectedAmounts, _Selectors.getBulkNames, function (item, selectedAmounts, bulkNames) {
  var bulkNameErrors = [];
  var children = (0, _get["default"])(item, 'itemGroup.children', []);
  var _iterator = _createForOfIteratorHelper(children),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var childItem = _step.value;
      if (childItem.itemGroup && childItem.itemGroup.identifier === 'size') {
        var _iterator2 = _createForOfIteratorHelper(childItem.itemGroup.children),
          _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var sizeChildItem = _step2.value;
            var selectedAmount = (0, _get["default"])(selectedAmounts, sizeChildItem.identifier, 0);
            var childBulkNames = (0, _get["default"])(bulkNames, sizeChildItem.identifier, []);
            if (selectedAmount > 0 && childBulkNames.length !== selectedAmount) {
              bulkNameErrors.push((0, _i18n.t)('receiveOfferForm.checkBulkNamesInputs', {
                item: item.title + ' / ' + (0, _upperFirst["default"])(childItem.itemgroupentryTitle) + ' / ' + sizeChildItem.itemgroupentryTitle
              }));
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
      } else {
        var _selectedAmount = (0, _get["default"])(selectedAmounts, childItem.identifier, 0);
        var _childBulkNames = (0, _get["default"])(bulkNames, childItem.identifier, []);
        if (_selectedAmount > 0 && _childBulkNames.length !== _selectedAmount) {
          bulkNameErrors.push((0, _i18n.t)('receiveOfferForm.checkBulkNamesInputs', {
            item: item.title + ' / ' + (0, _upperFirst["default"])(childItem.itemgroupentryTitle)
          }));
        }
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return bulkNameErrors;
});
var createPricePropsFromState = exports.createPricePropsFromState = (0, _createSelector["default"])(_Selectors.getCalculation, _Selectors.getUserSelectedCalculation, function (calculation, userSelectedCalculation) {
  var displayNetPrices = (0, _configuration.getConf)('displayNetPrices', false);
  var props = {
    priceList: [],
    priceFormatted: displayNetPrices ? (0, _get["default"])(calculation, 'netTotalFormatted', '') : (0, _get["default"])(calculation, 'totalFormatted', ''),
    error: null,
    bulkSavings: [],
    notifications: []
  };
  var positions = (0, _get["default"])(calculation, 'positions');
  if ((0, _isArray["default"])(positions)) {
    props.priceList = positions.map(function (p) {
      return {
        key: p.calculationTypeIdentifier,
        selectable: p.selectableByUser,
        selected: (0, _get["default"])(userSelectedCalculation, p.calculationTypeIdentifier, false),
        label: p.title || (0, _i18n.t)("calculationTypes.".concat(p.calculationTypeIdentifier)),
        price: displayNetPrices ? p.priceNetFormatted : p.priceFormatted
      };
    });
  }
  var bulkSavings = (0, _get["default"])(calculation, 'bulkSavings');
  if ((0, _isArray["default"])(bulkSavings)) {
    props.bulkSavings = bulkSavings.map(function (b) {
      return {
        key: b.itemIdentifier,
        itemTitle: b.itemTitle,
        savingsBulkAmount: b.savingsBulkAmount,
        savingAmount: b.savingAmount
      };
    });
  }
  if (calculation && calculation.success === false) {
    props.error = {
      code: calculation.code,
      errors: calculation.errors
    };
  }
  if (props.error && props.error.errors.length) {
    var uniqErrors = (0, _uniqBy["default"])(props.error.errors, 'itemIdentifier');
    var _iterator3 = _createForOfIteratorHelper(uniqErrors),
      _step3;
    try {
      for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
        var fieldError = _step3.value;
        props.notifications.push({
          message: (0, _i18n.t)('amountPrice.minimumAmountError', {
            minimumAmount: fieldError.minimumAmount,
            itemTitle: fieldError.itemTitle,
            selectedAmount: fieldError.selectedAmount
          }),
          level: 'error',
          color: 'error'
        });
      }
    } catch (err) {
      _iterator3.e(err);
    } finally {
      _iterator3.f();
    }
  }
  props.bulkSavings.length > 0 && props.bulkSavings.map(function (bulkSaving) {
    props.notifications.push({
      message: (0, _i18n.t)('amountPrice.bulkSavings', {
        itemTitle: bulkSaving.itemTitle,
        savingsBulkAmount: bulkSaving.savingsBulkAmount,
        savingAmount: bulkSaving.savingAmount
      }),
      level: 'info',
      color: 'default'
    });
  });
  return props;
});
var mapStateToProps = function mapStateToProps(_ref) {
  var configurator = _ref.configurator,
    configurationMode = _ref.configurationMode,
    ui = _ref.ui;
  var priceProps = createPricePropsFromState(configurator);
  var _getAvailableConfigur = (0, _Selectors4.getAvailableConfigurationModes)({
      configurationMode: configurationMode
    }),
    designerAvailable = _getAvailableConfigur.designer;
  if (!designerAvailable) {
    // remove user selectable designer global calculation post from priceList for only creator Product
    priceProps = _objectSpread(_objectSpread({}, priceProps), {}, {
      priceList: priceProps.priceList.filter(function (listItem) {
        return !listItem.key.startsWith('global') && listItem.selectableByUser === true;
      })
    });
  }
  var query = new URLSearchParams(location.search);
  return _objectSpread(_objectSpread(_objectSpread({
    Component: _AmountPriceAdminareaWrapper.AmountPriceAdminareaWrapper,
    AmountPriceComponent: _AmountPrice["default"],
    vatNotice: !(0, _configuration.getConf)('displayNetPrices', false) ? (0, _i18n.t)('amountPrice.vatNotice') : (0, _i18n.t)('amountPrice.vatNoticeNet'),
    boxed: true,
    showProductVariants: true,
    showReceiveOfferForm: query.has('_cta_element') ? query.get('_cta_element') === 'requestOffer' : (0, _Selectors.showReceiveOfferForm)(configurator),
    showCallToAction: query.has('_cta_element') ? query.get('_cta_element') !== 'none' : (0, _Selectors.showCallToAction)(configurator),
    skipPriceOverview: query.has('_skipcartoverlay'),
    displayAcceptDesign: !designerAvailable ? false : (0, _configuration.getConf)('displayAcceptDesign', true),
    isBulkNamesSelected: (0, _Selectors3.isBulkNamesSelected)(configurator),
    bulkNameErrors: (0, _Selectors3.isBulkNamesSelected)(configurator) ? createBulkNameErrors(configurator) : null
  }, createAmountPropsFromState(configurator)), priceProps), {}, {
    clientTexts: (0, _Selectors.getClientTexts)(configurator),
    addToCartPopUpLoader: (0, _Selectors2.getVisibilityMapProperty)(ui, 'addToCartPopUpLoader'),
    userComment: (0, _get["default"])(configurator, 'configuration.customdata.comment', ''),
    userConfiguration: (0, _Selectors.getConfiguration)(configurator),
    isCreator: (0, _Selectors4.isCreatorModeSelected)({
      configurationMode: configurationMode
    })
  });
};
var mapDispatchToProps = function mapDispatchToProps() {
  return {
    onSelectableChanged: function onSelectableChanged(identifier, value) {
      return _ServiceLocator.Services.configurator.setSelectedCalculation(identifier, value);
    },
    onClose: function onClose() {
      _ServiceLocator.Services.visualization.abortScreenshotting();
    },
    onChangeAmount: function onChangeAmount(amount) {
      return _ServiceLocator.Services.configurator.setSelectedAmount(false, amount);
    },
    sendReceiveOfferRequest: function sendReceiveOfferRequest(data) {
      return _ServiceLocator.Services.interaction.sendReceiveOfferRequest(data);
    },
    setConfigurationComment: function setConfigurationComment(notice) {
      return _ServiceLocator.Services.configurator.setConfigurationComment(notice);
    },
    onAddToBasket: function onAddToBasket() {
      return _ServiceLocator.Services.interaction.addToCart();
    },
    onShowChange: function onShowChange(on) {
      return _ServiceLocator.Services.configurator.setCalculationAutoResolveEnabled(!on);
    },
    validateConfiguration: function validateConfiguration() {
      return (0, _configuration.getConf)('validateBeforeCTA') && _ServiceLocator.Services.configurator.validateConfiguration();
    },
    toggleGlobalLoader: function toggleGlobalLoader(on) {
      return _ServiceLocator.Services.ui.toggle('globalLoader', on);
    }
  };
};
var _default = exports["default"] = (0, _ComponentContainer.containerConnect)(mapStateToProps, mapDispatchToProps);