"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _get = _interopRequireDefault(require("lodash/get"));
var _find = _interopRequireDefault(require("lodash/find"));
var _map = _interopRequireDefault(require("lodash/map"));
var _keys2 = _interopRequireDefault(require("lodash/keys"));
var _isEqual = _interopRequireDefault(require("lodash/isEqual"));
var _difference = _interopRequireDefault(require("lodash/difference"));
var _omit = _interopRequireDefault(require("lodash/omit"));
var _debounce = _interopRequireDefault(require("lodash/debounce"));
var _AbstractConfiguratorService = _interopRequireDefault(require("../../Framework/Services/AbstractConfiguratorService"));
var _Actions = _interopRequireWildcard(require("../Reducers/Configurator/Actions"));
var configuratorActions = _Actions;
var _Selectors = require("../Reducers/Configurator/Selectors");
var _Selectors2 = require("../Reducers/DesignArea/Selectors");
var _Actions2 = require("../Reducers/UI/Actions");
var _Selectors3 = require("../Reducers/Fonts/Selectors");
var _ServiceLocator = require("../ServiceLocator");
var _configuration2 = require("../configuration");
var _Reducer = require("../Reducers/DesignData/Reducer");
var _cached = require("../../Utils/Function/cached");
var _getFirstDataURLFromScreenshotsObj = require("../Modules/Visualization/Utils/getFirstDataURLFromScreenshotsObj");
var _Selectors4 = require("../Reducers/DesignData/Selectors");
var _createMessageInterface = _interopRequireWildcard(require("../Utils/createMessageInterface"));
var _SvgFixers = require("../Modules/Designer/Utils/SvgFixers");
var _excluded = ["code"];
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t2 in e) "default" !== _t2 && {}.hasOwnProperty.call(e, _t2) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t2)) && (i.get || i.set) ? o(f, _t2, i) : f[_t2] = e[_t2]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
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); }
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 _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; }
function _regeneratorRuntime() { "use strict"; var r = _regenerator(), e = r.m(_regeneratorRuntime), t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor; function n(r) { var e = "function" == typeof r && r.constructor; return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name)); } var o = { "throw": 1, "return": 2, "break": 3, "continue": 3 }; function a(r) { var e, t; return function (n) { e || (e = { stop: function stop() { return t(n.a, 2); }, "catch": function _catch() { return n.v; }, abrupt: function abrupt(r, e) { return t(n.a, o[r], e); }, delegateYield: function delegateYield(r, o, a) { return e.resultName = o, t(n.d, _regeneratorValues(r), a); }, finish: function finish(r) { return t(n.f, r); } }, t = function t(r, _t, o) { n.p = e.prev, n.n = e.next; try { return r(_t, o); } finally { e.next = n.n; } }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n; try { return r.call(this, e); } finally { n.p = e.prev, n.n = e.next; } }; } return (_regeneratorRuntime = function _regeneratorRuntime() { return { wrap: function wrap(e, t, n, o) { return r.w(a(e), t, n, o && o.reverse()); }, isGeneratorFunction: n, mark: r.m, awrap: function awrap(r, e) { return new _OverloadYield(r, e); }, AsyncIterator: _regeneratorAsyncIterator, async: function async(r, e, t, o, u) { return (n(e) ? _regeneratorAsyncGen : _regeneratorAsync)(a(r), e, t, o, u); }, keys: _regeneratorKeys, values: _regeneratorValues }; })(); }
function _regeneratorValues(e) { if (null != e) { var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"], r = 0; if (t) return t.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) return { next: function next() { return e && r >= e.length && (e = void 0), { value: e && e[r++], done: !e }; } }; } throw new TypeError(_typeof(e) + " is not iterable"); }
function _regeneratorKeys(e) { var n = Object(e), r = []; for (var t in n) r.unshift(t); return function e() { for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e; return e.done = !0, e; }; }
function _regeneratorAsync(n, e, r, t, o) { var a = _regeneratorAsyncGen(n, e, r, t, o); return a.next().then(function (n) { return n.done ? n.value : a.next(); }); }
function _regeneratorAsyncGen(r, e, t, o, n) { return new _regeneratorAsyncIterator(_regenerator().w(r, e, t, o), n || Promise); }
function _regeneratorAsyncIterator(t, e) { function n(r, o, i, f) { try { var c = t[r](o), u = c.value; return u instanceof _OverloadYield ? e.resolve(u.v).then(function (t) { n("next", t, i, f); }, function (t) { n("throw", t, i, f); }) : e.resolve(u).then(function (t) { c.value = t, i(c); }, function (t) { return n("throw", t, i, f); }); } catch (t) { f(t); } } var r; this.next || (_regeneratorDefine2(_regeneratorAsyncIterator.prototype), _regeneratorDefine2(_regeneratorAsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () { return this; })), _regeneratorDefine2(this, "_invoke", function (t, o, i) { function f() { return new e(function (e, r) { n(t, i, e, r); }); } return r = r ? r.then(f, f) : f(); }, !0); }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function _OverloadYield(e, d) { this.v = e, this.k = d; }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), 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 _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(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 getSelectedAmountsBySizes = function getSelectedAmountsBySizes(item, selectedAmounts) {
  var itemGroupMap = function itemGroupMap(rootItem, fn) {
    var data = [];
    if ((0, _get["default"])(rootItem, 'itemGroup.children.length', 0) > 0) {
      var _iterator = _createForOfIteratorHelper(rootItem.itemGroup.children),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var _item = _step.value;
          var mappedData = fn(_item, data);
          mappedData && data.push(mappedData);
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }
    return data;
  };
  return itemGroupMap(item, function (colorGroupItem) {
    return {
      identifier: colorGroupItem.identifier,
      amount: (0, _get["default"])(selectedAmounts, colorGroupItem.identifier, 0),
      sizes: itemGroupMap(colorGroupItem, function (sizeGroupItem) {
        return {
          amount: (0, _get["default"])(selectedAmounts, sizeGroupItem.identifier, 0),
          identifier: sizeGroupItem.identifier
        };
      })
    };
  });
};
var ConfiguratorService = exports["default"] = /*#__PURE__*/function (_AbstractConfigurator) {
  _inherits(ConfiguratorService, _AbstractConfigurator);
  var _super = _createSuper(ConfiguratorService);
  function ConfiguratorService() {
    var _this;
    _classCallCheck(this, ConfiguratorService);
    _this = _super.call(this);
    _ServiceLocator.Services.store.observeStore(function (state) {
      return state.configurator.configuration;
    }, function () {
      // since it's debounced, the prevConfiguration should be the configuration from the latest call
      var prevConfiguration = {};
      return (0, _debounce["default"])(function (configuration) {
        _this.onConfigurationChange(configuration, prevConfiguration);
        prevConfiguration = configuration;
      }, 300);
    }());
    return _this;
  }
  _createClass(ConfiguratorService, [{
    key: "init",
    value: function init() {
      var _this2 = this;
      var adminMode = (0, _configuration2.getConf)('adminMode');
      if (!adminMode) {
        var messageInterface = (0, _createMessageInterface["default"])();
        messageInterface.addListener(_createMessageInterface.LISTENER_SWITCH_OPTIONS, /*#__PURE__*/function () {
          var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(event) {
            var optionsJSON, optionsToSelect;
            return _regeneratorRuntime().wrap(function _callee$(_context) {
              while (1) switch (_context.prev = _context.next) {
                case 0:
                  optionsJSON = (0, _get["default"])(event, 'data.options');
                  try {
                    optionsToSelect = JSON.parse(optionsJSON);
                    _ServiceLocator.Services.store.dispatch((0, _Actions.selectMultipleOptions)(optionsToSelect));
                  } catch (e) {
                    // eslint-disable-next-line no-console
                    console.error('Wrong JSON provided for switch_options:', optionsJSON);
                  }
                case 2:
                case "end":
                  return _context.stop();
              }
            }, _callee);
          }));
          return function (_x) {
            return _ref.apply(this, arguments);
          };
        }());
        messageInterface.addListener(_createMessageInterface.LISTENER_SAVE_CONFIGURATION, /*#__PURE__*/function () {
          var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(event) {
            var save_id, saveType, configuration, code;
            return _regeneratorRuntime().wrap(function _callee2$(_context2) {
              while (1) switch (_context2.prev = _context2.next) {
                case 0:
                  save_id = (0, _get["default"])(event, 'data.save_id');
                  saveType = (0, _get["default"])(event, 'data.save_type') === _configuration2.SaveTypes.CART ? _configuration2.SaveTypes.CART : _configuration2.SaveTypes.USER;
                  _context2.prev = 2;
                  _context2.next = 5;
                  return _this2.captureAndSaveConfiguration(saveType);
                case 5:
                  configuration = _context2.sent;
                  code = (0, _get["default"])(configuration, 'data.code');
                  messageInterface.dispatch({
                    method: _createMessageInterface.METHOD_CONFIGURATION_SAVED_REMOTELY,
                    save_id: save_id,
                    code: code
                  });
                  _context2.next = 13;
                  break;
                case 10:
                  _context2.prev = 10;
                  _context2.t0 = _context2["catch"](2);
                  // eslint-disable-next-line no-console
                  console.error('Saving configuration failed, save_id was  ', save_id);
                case 13:
                case "end":
                  return _context2.stop();
              }
            }, _callee2, null, [[2, 10]]);
          }));
          return function (_x2) {
            return _ref2.apply(this, arguments);
          };
        }());
      }
    }

    // state selector
  }, {
    key: "state",
    get: function get() {
      return _ServiceLocator.Services.store.state.configurator;
    }
  }, {
    key: "initialize",
    value: function initialize() {
      var params = {};
      var basePath = (0, _configuration2.getConf)('routingBasePath', '/');
      var itemRegex = new RegExp("".concat(basePath, "(code|identifier):([^/]+)"));
      var results = itemRegex.exec(location.pathname);
      if (results) {
        params[results[1]] = results[2];
      }
      if (params.identifier) {
        this.setLoadIdentifier(params.identifier);
      } else if (params.code) {
        this.setLoadCode(params.code);
      }
      this.loadClientData();
    }
  }, {
    key: "prepareConfigurationForSave",
    value: function prepareConfigurationForSave() {
      var overwrite = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      var extraData = arguments.length > 1 ? arguments[1] : undefined;
      var configuration = this.state.configuration;
      var updatedConfiguration = _ServiceLocator.Services.designData.removeAllDesignAreaPlaceholders(configuration);

      // remove the code by default (to prevent overwriting the current configuration)
      var code = updatedConfiguration.code,
        otherData = _objectWithoutProperties(updatedConfiguration, _excluded);

      // always remove parentCode from customdata
      var customdata = (0, _omit["default"])(updatedConfiguration.customdata || {}, ['parentCode']);

      // add parentCode only when it's set in the config
      if ((0, _configuration2.getConf)('addParentCodeOnSave')) {
        customdata.parentCode = code;
      }
      return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, otherData), overwrite ? {
        code: code
      } : {}), extraData), {}, {
        customdata: customdata
      });
    }
  }, {
    key: "setCalculationAutoResolveEnabled",
    value: function setCalculationAutoResolveEnabled(enabled) {
      _ServiceLocator.Services.store.dispatch((0, _Actions.setCalculationAutoResolveEnabled)(enabled));
    }
  }, {
    key: "skipNextCalculationAutoResolve",
    value: function skipNextCalculationAutoResolve() {
      _ServiceLocator.Services.store.dispatch((0, _Actions.skipNextAutoResolve)());
    }
  }, {
    key: "onConfigurationChange",
    value: function () {
      var _onConfigurationChange = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(configuration, prevConfiguration) {
        return _regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              if (!(this.state.calculationIsEnabled && (!configuration.check_results ||
              // no check results
              configuration.check_results.status) &&
              // or the check result status is ok
              this.shouldInvalidateCalculation(prevConfiguration, configuration))) {
                _context3.next = 10;
                break;
              }
              if (!(0, _Selectors.isCalculationAutoResolveEnabled)(this.state)) {
                _context3.next = 8;
                break;
              }
              // disable automatic price updates to take direct control over error handling
              _ServiceLocator.Services.store.dispatch((0, _Actions.setCalculationEnabled)(false));
              // triggering the calculation directly to make sure it's synced
              _context3.next = 5;
              return _ServiceLocator.Services.store.dispatch(configuratorActions.doCalculation());
            case 5:
              _ServiceLocator.Services.store.dispatch((0, _Actions.setCalculationEnabled)(true));
              _context3.next = 10;
              break;
            case 8:
              _ServiceLocator.Services.store.dispatch(configuratorActions.invalidateCalculation());
              _ServiceLocator.Services.store.dispatch(configuratorActions.doCalculation());
            case 10:
              if (this.shouldUpdateVisualization(prevConfiguration, configuration)) {
                _ServiceLocator.Services.visualization.update(configuration);
              }
            case 11:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function onConfigurationChange(_x3, _x4) {
        return _onConfigurationChange.apply(this, arguments);
      }
      return onConfigurationChange;
    }()
  }, {
    key: "shouldInvalidateCalculation",
    value: function shouldInvalidateCalculation(prevConfiguration, configuration) {
      return this.isRoughEqual(configuration, prevConfiguration);
    }
  }, {
    key: "shouldUpdateVisualization",
    value: function shouldUpdateVisualization(prevConfiguration, configuration) {
      return this.isRoughEqual(configuration, prevConfiguration);
    }
  }, {
    key: "isRoughEqual",
    value: function isRoughEqual(configuration, prevConfiguration) {
      // calculation should be invalidated only when one of the relevant properties has changed
      var pc = this.getRoughConfiguration(prevConfiguration);
      var cc = this.getRoughConfiguration(configuration);
      return !(0, _isEqual["default"])(cc, pc);
    }

    /**
     * Returns the configuration core values
     * Use this method to create a more simple comparable object that represents the same
     * configuration
     * @param configuration
     * @returns {{item: {identifier: *, price: *}, optionclassifications: Array, designdata: {}, customdata: {}}}
     */
  }, {
    key: "getRoughConfiguration",
    value: function getRoughConfiguration(configuration) {
      var item = configuration.item,
        optionclassifications = configuration.optionclassifications,
        designdata = configuration.designdata;
      var customdata = configuration.customdata && (0, _omit["default"])(configuration.customdata, ['comment']);
      return {
        item: item && {
          identifier: item.identifier,
          price: item.price
        },
        optionclassifications: optionclassifications && (0, _map["default"])(optionclassifications, function (oc) {
          return {
            identifier: oc.identifier,
            selectedoptions: (0, _map["default"])(oc.selectedoptions, function (o) {
              return {
                identifier: o.identifier,
                amount: o.amount,
                price: o.price
              };
            })
          };
        }),
        designdata: designdata && this.getRoughDesignData(designdata),
        customdata: customdata
      };
    }

    /**
     * The design data can also invalidate the calculation if any of the relevant properties have changed.
     * (Eg. an object is added or removed, or a design area related option has changed.)
     * @param designData
     * @returns {null|object}
     */
  }, {
    key: "getRoughDesignData",
    value: function getRoughDesignData(designData) {
      if (!designData) {
        return null;
      }
      var designAreas = Object.keys(designData);
      var roughDesignData = {};
      for (var _i = 0, _designAreas = designAreas; _i < _designAreas.length; _i++) {
        var designAreaIdentifier = _designAreas[_i];
        var designAreaData = designData[designAreaIdentifier];
        var canvasData = designAreaData.canvasData,
          designProductionMethodIdentifier = designAreaData.designProductionMethodIdentifier,
          colorAmount = designAreaData.colorAmount;
        roughDesignData[designAreaIdentifier] = {
          objectCount: (0, _get["default"])(canvasData, 'objects.length'),
          designProductionMethodIdentifier: designProductionMethodIdentifier,
          colorAmount: colorAmount,
          objects: this.getRoughDesignDataObjectDetails(designAreaData)
        };
      }
      return roughDesignData;
    }
  }, {
    key: "getRoughDesignDataObjectDetails",
    value: function getRoughDesignDataObjectDetails(designData) {
      var includeMetricData = (0, _configuration2.getConf)('designer.includeMetricContentSize', false);
      return (0, _get["default"])(designData, 'canvasData.objects', []).map(function (object) {
        var _object$metric, _object$metric2, _object$metric3, _object$metric4;
        return _objectSpread({
          uuid: object.uuid
        }, includeMetricData ? {
          x: ((_object$metric = object.metric) === null || _object$metric === void 0 ? void 0 : _object$metric.x) || 0,
          y: ((_object$metric2 = object.metric) === null || _object$metric2 === void 0 ? void 0 : _object$metric2.y) || 0,
          width: ((_object$metric3 = object.metric) === null || _object$metric3 === void 0 ? void 0 : _object$metric3.width) || 0,
          height: ((_object$metric4 = object.metric) === null || _object$metric4 === void 0 ? void 0 : _object$metric4.height) || 0,
          rotation: object.rotation || 0
        } : {});
      });
    }

    //// <-- ACTIONS -->
  }, {
    key: "saveConfiguration",
    value: function () {
      var _saveConfiguration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(configuration, configurationtype) {
        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              return _context4.abrupt("return", _ServiceLocator.Services.store.dispatch(configuratorActions.saveConfiguration(configuration, configurationtype)));
            case 1:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }));
      function saveConfiguration(_x5, _x6) {
        return _saveConfiguration.apply(this, arguments);
      }
      return saveConfiguration;
    }()
  }, {
    key: "getPreviewImagesForVariants",
    value: function () {
      var _getPreviewImagesForVariants = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
        var options,
          _options$size,
          size,
          designData,
          configurationOptions,
          cached,
          memo,
          designAreas,
          defaultDesignAreaIdentifier,
          areasWithDesign,
          screenshotAreaIdentifier,
          usedAreas,
          firstDesignViewIdentifier,
          usedViews,
          variants,
          screenshots,
          images,
          _args5 = arguments;
        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              options = _args5.length > 0 && _args5[0] !== undefined ? _args5[0] : {};
              _ServiceLocator.Services.designData.closeDesignAreaEditor();
              _ServiceLocator.Services.designData.clearDesignAreaSelection();
              _options$size = options.size, size = _options$size === void 0 ? {
                width: 100,
                height: 100
              } : _options$size;
              designData = (0, _Reducer.getDesignData)(this.state);
              configurationOptions = (0, _Selectors.getConfiguration)(this.state).optionclassifications;
              cached = (0, _cached.getCached)('variantPreviewImages', designData, configurationOptions);
              if (!cached.validate()) {
                _context5.next = 9;
                break;
              }
              return _context5.abrupt("return", cached.getValue());
            case 9:
              memo = _ServiceLocator.Services.designData.createHighlightMemo(false);
              designAreas = _ServiceLocator.Services.store.state.designArea.filteredDesignAreas; // use the first area as default if it's not defined through the production methods
              defaultDesignAreaIdentifier = (0, _Selectors2.getDefaultDesignAreaIdentifierFromProductionMethod)(_ServiceLocator.Services.store.state) || (designAreas.length ? designAreas[0].identifier : null);
              areasWithDesign = designData && Object.keys(designData).filter(function (designAreaIdentifier) {
                return (0, _get["default"])(designData[designAreaIdentifier], 'canvasData.objects.length');
              }); // use the default design area, or the first that contains a design
              screenshotAreaIdentifier = areasWithDesign && (areasWithDesign.indexOf(defaultDesignAreaIdentifier) !== -1 ? defaultDesignAreaIdentifier : areasWithDesign[0]) || defaultDesignAreaIdentifier;
              usedAreas = screenshotAreaIdentifier ? [screenshotAreaIdentifier] : [];
              firstDesignViewIdentifier = (0, _Selectors2.getCameraViewListForDesignAreaList)(designAreas, usedAreas).pop();
              usedViews = [firstDesignViewIdentifier];
              variants = (0, _Selectors.getChildren)(this.state).map(function (_ref3) {
                var identifier = _ref3.identifier;
                return identifier;
              });
              if (!variants[0]) {
                variants = [(0, _Selectors.getItem)(this.state).identifier];
              }
              _context5.prev = 19;
              _context5.next = 22;
              return _ServiceLocator.Services.visualization.getScreenshots({
                areaList: usedAreas,
                viewList: usedViews,
                variantList: variants,
                size: size
              });
            case 22:
              screenshots = _context5.sent;
              if (screenshots) {
                _context5.next = 25;
                break;
              }
              return _context5.abrupt("return", {});
            case 25:
              images = {};
              Object.keys(screenshots).forEach(function (identifier) {
                images[variants.length === 1 ? variants[0] : identifier] = (0, _getFirstDataURLFromScreenshotsObj.getFirstDataURLFromScreenshotsObj)(screenshots[identifier]);
              });
              cached.setValue(images);
              return _context5.abrupt("return", images);
            case 31:
              _context5.prev = 31;
              _context5.t0 = _context5["catch"](19);
              // eslint-disable-next-line no-console
              console.error('Error occurred while generating preview images:', _context5.t0);
            case 34:
              _context5.prev = 34;
              memo.restore();
              return _context5.finish(34);
            case 37:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this, [[19, 31, 34, 37]]);
      }));
      function getPreviewImagesForVariants() {
        return _getPreviewImagesForVariants.apply(this, arguments);
      }
      return getPreviewImagesForVariants;
    }()
  }, {
    key: "togglePlaceholders",
    value: function togglePlaceholders(show) {
      var _this3 = this;
      var canvases = _ServiceLocator.Services.designData.getDesignAreaCanvases();
      canvases.forEach(function (_ref4) {
        var canvas = _ref4.canvas;
        var _iterator2 = _createForOfIteratorHelper(canvas.objects),
          _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var obj = _step2.value;
            if ((0, _Selectors4.isPlaceholderObject)(obj)) {
              obj.wrappedObject.visible = show;
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
      });
      return function () {
        return _this3.togglePlaceholders(true);
      };
    }
  }, {
    key: "createMediaDataForConfiguration",
    value: function () {
      var _createMediaDataForConfiguration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(configuration) {
        var mediaData, restorePlaceholderVisibility, memo, fontMapping, svgs, fullSvgs, usedAreas, designArea, filteredDesignAreas, usedViews, item, selectedAmounts, selectedVariants, selectedVariant, designViewList, screenshots, _iterator4, _step4, variant, variantImages, _keys, orderedImages, index, key;
        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              mediaData = {};
              restorePlaceholderVisibility = this.togglePlaceholders(false);
              memo = _ServiceLocator.Services.designData.createHighlightMemo(false);
              fontMapping = (0, _Selectors3.getFontMapping)(_ServiceLocator.Services.store.state);
              _context6.next = 6;
              return _ServiceLocator.Services.designData.getScreenshotsOfElements(fontMapping);
            case 6:
              svgs = _context6.sent;
              mediaData.designDataSnapshots = (0, _SvgFixers.prepareDesignDataSnapshots)(svgs);
              _context6.next = 10;
              return _ServiceLocator.Services.designData.getScreenshots(fontMapping);
            case 10:
              fullSvgs = _context6.sent;
              mediaData.printDesignData = (0, _SvgFixers.preparePrintDesignData)(fullSvgs);
              usedAreas = Object.keys(fullSvgs);
              designArea = _ServiceLocator.Services.store.state.designArea;
              filteredDesignAreas = designArea.filteredDesignAreas;
              usedViews = (0, _Selectors2.getCameraViewListForDesignAreaList)(filteredDesignAreas, usedAreas);
              item = (0, _Selectors.getItem)(this.state);
              selectedAmounts = (0, _Selectors.getSelectedAmounts)(this.state);
              selectedVariants = getSelectedAmountsBySizes(item, selectedAmounts).filter(function (item) {
                if (item.sizes.length > 0) {
                  var _iterator3 = _createForOfIteratorHelper(item.sizes),
                    _step3;
                  try {
                    for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
                      var size = _step3.value;
                      if (size.amount > 0) {
                        return true;
                      }
                    }
                  } catch (err) {
                    _iterator3.e(err);
                  } finally {
                    _iterator3.f();
                  }
                } else {
                  if (item.amount > 0) {
                    return true;
                  }
                }
                return false;
              }).map(function (item) {
                return item.identifier;
              });
              selectedVariant = (0, _Selectors.getSelectedVariantIdentifier)(this.state);
              if (selectedVariants.length === 0) {
                selectedVariants.push(selectedVariant);
              }
              designViewList = (0, _Selectors2.getDesignViewListForDesignAreas)(_ServiceLocator.Services.store.state);
              mediaData.screenshots = {};
              _context6.prev = 23;
              _context6.next = 26;
              return _ServiceLocator.Services.visualization.getScreenshots({
                areaList: usedAreas,
                // used in 2D visualization
                viewList: usedViews,
                // used in 3D visualization
                variantList: selectedVariants,
                designViewList: designViewList // used in 2D visualization
              });
            case 26:
              screenshots = _context6.sent;
              if (screenshots) {
                // make sure the order is kept on the server side
                _iterator4 = _createForOfIteratorHelper(selectedVariants);
                try {
                  for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
                    variant = _step4.value;
                    variantImages = screenshots[variant];
                    if (variantImages) {
                      _keys = Object.keys(variantImages);
                      orderedImages = {};
                      for (index = 0; index < _keys.length; index++) {
                        key = _keys[index];
                        orderedImages[index + key] = variantImages[key];
                      }
                      screenshots[variant] = orderedImages;
                    }
                  }
                } catch (err) {
                  _iterator4.e(err);
                } finally {
                  _iterator4.f();
                }
              }
              mediaData.screenshots = screenshots;
              _context6.next = 34;
              break;
            case 31:
              _context6.prev = 31;
              _context6.t0 = _context6["catch"](23);
              // do not save in case of an error while generating screenshots
              // eslint-disable-next-line no-console
              console.error('Error occurred while generating screenshots:', _context6.t0);
            case 34:
              memo.restore();
              if (_typeof(configuration) === 'object') {
                Object.assign(configuration, mediaData);
              }
              restorePlaceholderVisibility();
              return _context6.abrupt("return", mediaData);
            case 38:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this, [[23, 31]]);
      }));
      function createMediaDataForConfiguration(_x7) {
        return _createMediaDataForConfiguration.apply(this, arguments);
      }
      return createMediaDataForConfiguration;
    }()
  }, {
    key: "captureAndSaveConfiguration",
    value: function () {
      var _captureAndSaveConfiguration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(saveType) {
        var extraData,
          configuration,
          _args7 = arguments;
        return _regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              extraData = _args7.length > 1 && _args7[1] !== undefined ? _args7[1] : {};
              _context7.prev = 1;
              _context7.next = 4;
              return this.editNameAsync(saveType);
            case 4:
              _context7.next = 10;
              break;
            case 6:
              _context7.prev = 6;
              _context7.t0 = _context7["catch"](1);
              // do not save if the name is not entered / confirmed
              // eslint-disable-next-line no-console
              console.error('Custom name editor not confirmed!');
              return _context7.abrupt("return");
            case 10:
              configuration = this.prepareConfigurationForSave(false, extraData);
              _context7.next = 13;
              return this.createMediaDataForConfiguration(configuration);
            case 13:
              return _context7.abrupt("return", this.saveConfiguration(configuration, saveType));
            case 14:
            case "end":
              return _context7.stop();
          }
        }, _callee7, this, [[1, 6]]);
      }));
      function captureAndSaveConfiguration(_x8) {
        return _captureAndSaveConfiguration.apply(this, arguments);
      }
      return captureAndSaveConfiguration;
    }()
  }, {
    key: "editNameAsync",
    value: function editNameAsync(saveType) {
      if ((0, _configuration2.getConf)('editCustomTitleBeforeSave') && (0, _configuration2.getConf)('customTitleSaveTypes').indexOf(saveType) !== -1) {
        _ServiceLocator.Services.ui.show('customTitleEditor');
        return _ServiceLocator.Services.async.create('customEditorConfirm');
      }
    }
  }, {
    key: "validateConfiguration",
    value: function validateConfiguration() {
      return _ServiceLocator.Services.store.dispatch((0, _Actions2.withGlobalLoader)(configuratorActions.validateConfiguration(this.state.configuration)));
    }
  }, {
    key: "saveAndReloadConfiguration",
    value: function () {
      var _saveAndReloadConfiguration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(saveType) {
        var tmpConfiguration, _configuration, _this$state, selectedoptionclassification, configuration, loadIdentifier, itemIdentifier;
        return _regeneratorRuntime().wrap(function _callee8$(_context8) {
          while (1) switch (_context8.prev = _context8.next) {
            case 0:
              if (!this.state.configuration.item.identifier) {
                _context8.next = 6;
                break;
              }
              tmpConfiguration = (0, _omit["default"])(this.state.configuration, ['code', 'date_created']);
              _context8.next = 4;
              return this.saveConfiguration(tmpConfiguration, saveType);
            case 4:
              _configuration = this.state.configuration;
              this.setLoadCode(_configuration.code);
            case 6:
              _this$state = this.state, selectedoptionclassification = _this$state.selectedoptionclassification, configuration = _this$state.configuration, loadIdentifier = _this$state.loadIdentifier;
              itemIdentifier = configuration.item.identifier || loadIdentifier; // item identifier is required for the following actions
              if (itemIdentifier) {
                _context8.next = 10;
                break;
              }
              return _context8.abrupt("return");
            case 10:
              // reload inspirations
              if ((0, _configuration2.getConf)('loadInspirations')) {
                this.loadInspirations(itemIdentifier);
              }

              // reload configuration variants
              this.loadConfigurationVariants(itemIdentifier);

              // the optionlist should be reloaded as well if open
              if (configuration.item.identifier && selectedoptionclassification.identifier) {
                this.loadOptions(configuration.item.identifier, selectedoptionclassification.identifier, configuration);
              }
            case 13:
            case "end":
              return _context8.stop();
          }
        }, _callee8, this);
      }));
      function saveAndReloadConfiguration(_x9) {
        return _saveAndReloadConfiguration.apply(this, arguments);
      }
      return saveAndReloadConfiguration;
    }()
  }, {
    key: "setLoadCode",
    value: function setLoadCode(code) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.setLoadCode(code));
    }
  }, {
    key: "setLoadIdentifier",
    value: function setLoadIdentifier(identifier) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.setLoadIdentifier(identifier));
    }
  }, {
    key: "loadInspirations",
    value: function loadInspirations(itemIdentifier) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.fetchInspirations(itemIdentifier));
    }
  }, {
    key: "loadConfigurationVariants",
    value: function loadConfigurationVariants(itemIdentifier) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.fetchConfigurationVariants(itemIdentifier));
    }
  }, {
    key: "loadOptions",
    value: function loadOptions(itemIdentifier, optionClassificationIdentifier, configuration) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.fetchOptions(itemIdentifier, optionClassificationIdentifier, configuration));
    }
  }, {
    key: "loadInitialOptions",
    value: function loadInitialOptions() {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.loadInitialOptionclassification(this.state.configuration));
    }
  }, {
    key: "loadInitialConfiguration",
    value: function loadInitialConfiguration() {
      return _ServiceLocator.Services.store.dispatch((0, _Actions2.withGlobalLoader)(configuratorActions.fetchInitialConfiguration()));
    }
  }, {
    key: "loadConfigurationForDesignerProductPreview",
    value: function loadConfigurationForDesignerProductPreview() {
      return _ServiceLocator.Services.store.dispatch((0, _Actions2.withGlobalLoader)(configuratorActions.fetchConfigurationForDesignerProductPreview()));
    }
  }, {
    key: "loadCodeSnippets",
    value: function loadCodeSnippets() {
      var _this4 = this;
      return _ServiceLocator.Services.store.dispatch(configuratorActions.fetchCodesnippets()).then(function (codeSnippets) {
        return _this4.attachCodeSnippets(codeSnippets);
      });
    }
  }, {
    key: "loadClientData",
    value: function loadClientData() {
      return _ServiceLocator.Services.store.dispatch((0, _Actions2.withGlobalLoader)(configuratorActions.fetchClientData()));
    }
  }, {
    key: "attachCodeSnippets",
    value: function attachCodeSnippets(codeSnippets) {
      if (codeSnippets.data.length > 0) {
        codeSnippets.data.forEach(function (_ref5) {
          var code = _ref5.code;
          var fragment = document.createRange().createContextualFragment(code);
          while (fragment.children.length > 0) {
            document.head.insertBefore(fragment.children[0], document.head.firstElementChild);
          }
        });
        window.dataLayer && _ServiceLocator.Services.analytics.setDataLayer(window.dataLayer);
      }
    }
  }, {
    key: "setSelectedAmount",
    value: function setSelectedAmount(identifier, amount) {
      var isUpdatedByUser = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      return _ServiceLocator.Services.store.dispatch(configuratorActions.setSelectedAmount(identifier || (0, _Selectors.getSelectedVariantIdentifier)(this.state) || this.state.configuration.item.identifier, amount, isUpdatedByUser));
    }
  }, {
    key: "updateSelectedAmount",
    value: function updateSelectedAmount(oldVariant, newVariant) {
      if (!(0, _Selectors.isSelectedAmountsUpdated)(this.state) && !(0, _Selectors.hasMultipleVariantsSelected)(this.state)) {
        if (!oldVariant.children && !newVariant.children && !oldVariant.itemGroup && !newVariant.itemGroup) {
          return _ServiceLocator.Services.store.dispatch(configuratorActions.switchSelectedAmount(oldVariant.identifier, newVariant.identifier));
        }
        var oldIdentifiers = (0, _Selectors.getDeepestChildIdentifiers)(oldVariant);
        var newIdentifiers = (0, _Selectors.getDeepestChildIdentifiers)(newVariant);
        var oldIdentifierKeys = (0, _keys2["default"])(oldIdentifiers);
        var newIdentifierKeys = (0, _keys2["default"])(newIdentifiers);
        var sortedOldIdentifierKeys = oldIdentifierKeys.sort(function (a, b) {
          return a.localeCompare(b, 0, {
            numeric: false
          });
        });
        var sortedNewIdentifierKeys = newIdentifierKeys.sort(function (a, b) {
          return a.localeCompare(b, 0, {
            numeric: false
          });
        });
        var identifierDiffs = (0, _difference["default"])(sortedOldIdentifierKeys, sortedNewIdentifierKeys);
        if (identifierDiffs.length === 0 && (0, _isEqual["default"])(sortedOldIdentifierKeys, sortedNewIdentifierKeys)) {
          for (var key in oldIdentifiers) {
            if (!oldIdentifiers.hasOwnProperty(key)) {
              continue;
            }
            if (newIdentifiers[key]) {
              _ServiceLocator.Services.store.dispatch(configuratorActions.switchSelectedAmount(oldIdentifiers[key], newIdentifiers[key]));
            }
          }
        }
      }
    }
  }, {
    key: "clearBulkNames",
    value: function clearBulkNames() {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.clearBulkNames());
    }
  }, {
    key: "saveBulkNames",
    value: function saveBulkNames(identifier, bulkNamesData) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.saveBulkNames(identifier, bulkNamesData));
    }
  }, {
    key: "switchSelectedAmount",
    value: function switchSelectedAmount(oldIdentifier, newIdentifier) {
      this.setSelectedVariantIdentifier(newIdentifier);
      var item = this.state.configuration.item;
      var oldVariant = (0, _find["default"])(item.itemGroup.children, function (o) {
        return o.identifier === oldIdentifier;
      });
      var newVariant = (0, _find["default"])(item.itemGroup.children, function (o) {
        return o.identifier === newIdentifier;
      });
      var selectedAmounts = (0, _Selectors.getSelectedAmounts)(this.state);
      var firstSelectedAmountIdentifier = (0, _keys2["default"])(selectedAmounts)[0];
      var oldSelectedAmountVariant = (0, _find["default"])(item.itemGroup.children, function (o) {
        if (o.itemGroup) {
          var children = o.itemGroup.children;
          return children.find(function (child) {
            return child.identifier === firstSelectedAmountIdentifier;
          });
        } else {
          return o.identifier === firstSelectedAmountIdentifier;
        }
      });
      if (!(0, _configuration2.getConf)('restrictAmountselectionToSelectedVariant', false)) {
        // Updates selected Amounts from previous selectedVariant amount to new variant
        this.updateSelectedAmount(oldSelectedAmountVariant, newVariant);
        return;
      }
      if (!oldVariant.children && !newVariant.children) {
        return _ServiceLocator.Services.store.dispatch(configuratorActions.switchSelectedAmount(oldVariant.identifier, newVariant.identifier));
      }
      var oldIdentifiers = (0, _Selectors.getDeepestChildIdentifiers)(oldVariant);
      var newIdentifiers = (0, _Selectors.getDeepestChildIdentifiers)(newVariant);
      for (var key in oldIdentifiers) {
        if (!oldIdentifiers.hasOwnProperty(key)) {
          continue;
        }
        if (newIdentifiers[key]) {
          _ServiceLocator.Services.store.dispatch(configuratorActions.switchSelectedAmount(oldIdentifiers[key], newIdentifiers[key]));
        }
      }
    }
  }, {
    key: "setConfigurationComment",
    value: function setConfigurationComment(comment) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.setComment(comment));
    }
  }, {
    key: "setSelectedCalculation",
    value: function setSelectedCalculation(identifier, value) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.setSelectedCalculation(identifier, value));
    }
  }, {
    key: "setSelectedVariantIdentifier",
    value: function setSelectedVariantIdentifier(identifier) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.setSelectedVariantIdentifier(identifier));
    }
  }, {
    key: "setOptionInputText",
    value: function setOptionInputText(identifier, value) {
      return _ServiceLocator.Services.store.dispatch(configuratorActions.setOptionInputText(identifier, value));
    }

    /**
     * A simple method for saving the configuration without any additional design data or screenshot
     * @param {string} saveType
     * @param {object} extraData
     * @returns {Promise}
     */
  }, {
    key: "prepareAndSaveConfiguration",
    value: function prepareAndSaveConfiguration(saveType) {
      var extraData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var configuration = this.prepareConfigurationForSave(false, extraData);
      return this.saveConfiguration(configuration, saveType);
    }
  }, {
    key: "addToCartCallback",
    value: function addToCartCallback(configuration) {
      // after saving call parent function if existing or send postMessage (depending on the configuration)
      if (window.parent !== undefined) {
        var addToCartMethod = (0, _configuration2.getConf)('addToCartMethod');
        if (addToCartMethod === 'postMessage' && window.parent.postMessage !== undefined) {
          var appConf = (0, _configuration2.getConf)();
          var targetOrigin = (0, _get["default"])(appConf, 'addToCartPostMessageTargetOrigin', '*');
          window.parent.postMessage({
            method: _createMessageInterface.METHOD_ADD_TO_CART,
            code: configuration.code
          }, targetOrigin);
        } else if (addToCartMethod === 'functionCall' && window.parent.addToCart !== undefined) {
          window.parent.addToCart(configuration.code);
        }
      }
    }
  }]);
  return ConfiguratorService;
}(_AbstractConfiguratorService["default"]);