"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.reversePointTransform = exports["default"] = void 0;
var _get = _interopRequireDefault(require("lodash/get"));
var _find = _interopRequireDefault(require("lodash/find"));
var _flow = _interopRequireDefault(require("lodash/flow"));
var _Constants = require("redhotmagma-visualization/Constants");
var _visualizationAdapterCreator = require("redhotmagma-visualization/visualizationAdapterCreator");
var _ExposedModules = require("redhotmagma-visualization/ExposedModules");
var _AbstractVisualizationService = _interopRequireDefault(require("../../Framework/Services/AbstractVisualizationService"));
var _i18n = require("../../Framework/i18n");
var _ServiceLocator = require("../ServiceLocator");
var _configuration = require("../configuration");
var _Selectors = require("../Reducers/DesignArea/Selectors");
var _Selectors2 = require("../Reducers/Configurator/Selectors");
var _sendMessage = _interopRequireDefault(require("../../Utils/Function/sendMessage"));
var _Observable = _interopRequireDefault(require("../../Utils/Decorators/Observable"));
var _NoVisualization = require("../Screens/Configurator/Components/NoVisualization/NoVisualization");
var _Selectors3 = require("../Reducers/DesignView/Selectors");
var _Selectors4 = require("../Reducers/ConfigurationMode/Selectors");
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 _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; }
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 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 _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 _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 _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); }
var EventTypes = {
  ComponentChange: 'VisualizationService/ComponentChange',
  VisualizationUpdate: 'VisualizationService/VisualizationUpdate'
};

// if the visualization script is configured, load it asap
var visualizationScriptSrc = (0, _configuration.getConf)('visualization.useVisualizationScript.src', false);
var visualizationScriptPromise = new Promise(function (resolve, reject) {
  if (!visualizationScriptSrc) {
    resolve();
  }
  var script = document.createElement('script');
  script.onload = resolve;
  script.onerror = reject;
  document.head.appendChild(script);
  script.src = visualizationScriptSrc;
});
var VisualizationService = exports["default"] = /*#__PURE__*/function (_AbstractVisualizatio) {
  _inherits(VisualizationService, _AbstractVisualizatio);
  var _super = _createSuper(VisualizationService);
  function VisualizationService() {
    var _this;
    _classCallCheck(this, VisualizationService);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    _defineProperty(_assertThisInitialized(_this), "observable", new _Observable["default"](_assertThisInitialized(_this)));
    _defineProperty(_assertThisInitialized(_this), "host", (0, _configuration.getConf)('network.host'));
    _defineProperty(_assertThisInitialized(_this), "adapterConfig", function () {
      var cfg = (0, _visualizationAdapterCreator.createAdapterConfig)({
        host: _this.host
      }, {
        "default": {
          Component: _NoVisualization.NoVisualization
        },
        '3dVariant': {
          basePath: "".concat(_this.host, "/content/3D")
        }
      });
      // mapping for backward compatibility
      return _objectSpread(_objectSpread({}, cfg), {}, {
        '3d': cfg['3dVariant'],
        '2d': cfg['2dVariant'],
        layer: cfg['2dLayer']
      });
    }());
    /**
     * Reference of the visualization instance
     * @type {null|object}
     * @private
     */
    _defineProperty(_assertThisInitialized(_this), "_component", null);
    /**
     * Function to release the camera movement restrictions
     * @type {null|function}
     * @private
     */
    _defineProperty(_assertThisInitialized(_this), "_removeRestrictedUserMovementZoomHandler", null);
    return _this;
  }
  _createClass(VisualizationService, [{
    key: "init",
    value: function init() {
      var _this2 = this;
      // skip initialization if the widget mode is active
      if (window.location.pathname.replace(/^\/([^/]*).*$/, '$1') === 'widget') {
        return;
      }
      _ServiceLocator.Services.store.observeStore(_Selectors2.getCurrentVisualizationSettings, function (target) {
        target !== 'fallback' && _this2.setComponent((0, _visualizationAdapterCreator.createVisualizationAdapter)(_this2.adapterConfig, target || 'default'));
      });
      _ServiceLocator.Services.store.observeStore((0, _flow["default"])(_Selectors2.getConfigurator, _Selectors2.getItem, function (_ref) {
        var parentItemIdentifier = _ref.parentItemIdentifier;
        return parentItemIdentifier;
      }), function (itemIdentifier) {
        (0, _sendMessage["default"])(_this2.getComponent(), 'updateItemPath', itemIdentifier);
      });
      _ServiceLocator.Services.store.observeStore((0, _flow["default"])(_Selectors2.getConfigurator, _Selectors2.getSelectedVariantIdentifier), function (variantIdentifier) {
        (0, _sendMessage["default"])(_this2.getComponent(), 'updateMaterialVariantPath', variantIdentifier);
      });
      _ServiceLocator.Services.store.observeStore(_Selectors.getSelectedDesignArea, this.designAreaChangeHandler.bind(this));
      _ServiceLocator.Services.store.observeStore(function (state) {
        return state.designView.selectedDesignView;
      }, function () {
        _this2.designViewChangeHandler((0, _Selectors3.getCurrentDesignView)(_ServiceLocator.Services.store.state));
      });
      _ServiceLocator.Services.store.observeStore(_Selectors4.getSelectedConfigurationMode, this.configurationModeChangeHandler.bind(this));
    }
  }, {
    key: "configurationModeChangeHandler",
    value: function configurationModeChangeHandler(mode) {
      _ServiceLocator.Services.designData.clearDesignAreaSelection();
      this.initDesignAreaInteraction(mode);
    }
  }, {
    key: "updateDesignAreaList",
    value: function () {
      var _updateDesignAreaList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(designAreaList) {
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return (0, _sendMessage["default"])(this.getComponent(), 'updateDesignAreaList', designAreaList);
            case 2:
              _context.next = 4;
              return this.designViewChangeHandler((0, _Selectors3.getCurrentDesignView)(_ServiceLocator.Services.store.state));
            case 4:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function updateDesignAreaList(_x) {
        return _updateDesignAreaList.apply(this, arguments);
      }
      return updateDesignAreaList;
    }()
  }, {
    key: "isReadyToRender",
    value: function isReadyToRender() {
      return (0, _sendMessage["default"])(this.getComponent(), 'isInitialized');
    }
  }, {
    key: "isReadyToRenderCustomDesign",
    value: function isReadyToRenderCustomDesign() {
      return (0, _sendMessage["default"])(this.getComponent(), 'isCustomizableMaterialAvailable');
    }
  }, {
    key: "render",
    value: function render() {
      return (0, _sendMessage["default"])(this.getComponent(), 'render');
    }
  }, {
    key: "update2DMaxZoom",
    value: function update2DMaxZoom(maxZoom) {
      return (0, _sendMessage["default"])(this.getComponent(), 'updateMaxZoomSetting', maxZoom);
    }
  }, {
    key: "updateVariant",
    value: function updateVariant(variantIdentifier) {
      return (0, _sendMessage["default"])(this.getComponent(), 'updateMaterialVariantPath', variantIdentifier);
    }
  }, {
    key: "setActiveDesignArea",
    value: function setActiveDesignArea(designArea) {
      return (0, _sendMessage["default"])(this.getComponent(), 'setActiveDesignArea', designArea);
    }
  }, {
    key: "getActiveDesignArea",
    value: function getActiveDesignArea() {
      return (0, _sendMessage["default"])(this.getComponent(), 'getActiveDesignArea');
    }
  }, {
    key: "designAreaChangeHandler",
    value: function () {
      var _designAreaChangeHandler = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
        var designArea, visualization, state, modeCheck, viewName;
        return _regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              designArea = (0, _Selectors.getSelectedDesignArea)(_ServiceLocator.Services.store.state);
              visualization = this.getComponent();
              this.setActiveDesignArea(designArea);
              state = _ServiceLocator.Services.store.state;
              modeCheck = (0, _Selectors2.visualizationModeCheck)(state);
              if (!modeCheck.is3D()) {
                _context2.next = 11;
                break;
              }
              viewName = (0, _Selectors.getSelectedViewName)(designArea);
              _context2.next = 9;
              return (0, _sendMessage["default"])(visualization, 'jumpToView', viewName);
            case 9:
              _context2.next = 14;
              break;
            case 11:
              if (!(modeCheck.is2D() && designArea.identifier)) {
                _context2.next = 14;
                break;
              }
              _context2.next = 14;
              return (0, _sendMessage["default"])(visualization, 'jumpToArea', designArea.identifier);
            case 14:
              // make sure every state update and change event is triggered before updating the visualization
              // root case: get the canvas data with cleared selection
              setTimeout(function () {
                return _ServiceLocator.Services.designData.updateVisualization();
              });
            case 15:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function designAreaChangeHandler() {
        return _designAreaChangeHandler.apply(this, arguments);
      }
      return designAreaChangeHandler;
    }()
  }, {
    key: "getViewChangedPromise",
    value: function getViewChangedPromise() {
      return this._viewChangedPromise;
    }
  }, {
    key: "designViewChangeHandler",
    value: function () {
      var _designViewChangeHandler = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(designView) {
        var visualization;
        return _regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              if (designView) {
                _context3.next = 2;
                break;
              }
              return _context3.abrupt("return");
            case 2:
              visualization = this.getComponent();
              this._viewChangedPromise = (0, _sendMessage["default"])(visualization, 'setView', designView);
              _context3.next = 6;
              return this._viewChangedPromise;
            case 6:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function designViewChangeHandler(_x2) {
        return _designViewChangeHandler.apply(this, arguments);
      }
      return designViewChangeHandler;
    }()
  }, {
    key: "setComponent",
    value: function setComponent(component) {
      var _this3 = this;
      if (!component) {
        throw new Error('Component must be provided!');
      }
      (0, _sendMessage["default"])(this._component, 'dispose');
      this._component = component;
      visualizationScriptPromise === null || visualizationScriptPromise === void 0 || visualizationScriptPromise.then(function () {
        var _window$initVisualiza, _window;
        (_window$initVisualiza = (_window = window).initVisualizationScript) === null || _window$initVisualiza === void 0 || _window$initVisualiza.call(_window, component, {
          THREE: _ExposedModules.THREE,
          TWEEN: _ExposedModules.TWEEN
        });
      })["catch"](function (e) {
        // eslint-disable-next-line no-console
        console.error('Error while loading visualization script', e);
      });
      if ((0, _Selectors2.isDesignerProductPreviewMode)()) {
        (0, _sendMessage["default"])(component, 'init');
        (0, _sendMessage["default"])(component, 'setSize', {
          width: 10,
          height: 10
        });
      }

      // add listener to the three adapter to catch intersections with the pointer
      component.observable.on(_Constants.EventTypes.Intersection, function (evt) {
        if (_ServiceLocator.Services.designData.handleCloseIfNeeded()) {
          // if it performed any actions, just return
          return;
        }

        // get the texture data from the intersection
        var getTextureHit = evt.data.getTextureHit;
        // so we can test if a design area was clicked
        var area = _this3.testTextureIntersection(getTextureHit());
        if (area) {
          // the design area change already invokes the jumpToView function
          _ServiceLocator.Services.designData.selectDesignArea(area.identifier);
        } else {
          // clear the selection if the click did not hit the area
          _ServiceLocator.Services.designData.clearDesignAreaSelection();
        }
      });

      // add click-away listener too, so the design area selection can be cleared
      component.observable.on(_Constants.EventTypes.ClickAway, function () {
        _ServiceLocator.Services.designData.handleCloseIfNeeded();
      });
      this.addAreaHoverHandler(component);

      // the design areas should be redrawn when the material is updated
      component.observable.on(_Constants.EventTypes.MaterialUpdated, /*#__PURE__*/function () {
        var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(updateEventObject) {
          return _regeneratorRuntime().wrap(function _callee4$(_context4) {
            while (1) switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return _ServiceLocator.Services.designData.updateVisualization(updateEventObject);
              case 2:
                _this3.observable.dispatch(EventTypes.VisualizationUpdate, updateEventObject);
              case 3:
              case "end":
                return _context4.stop();
            }
          }, _callee4);
        }));
        return function (_x3) {
          return _ref2.apply(this, arguments);
        };
      }());
      component.observable.on(_Constants.EventTypes.LoadStart, function () {
        _ServiceLocator.Services.ui.show('loadVisualization');
      });
      component.observable.on(_Constants.EventTypes.LoadFinished, function () {
        _ServiceLocator.Services.ui.hide('loadVisualization');
      });
      component.observable.on(_Constants.EventTypes.LoadError, function () {
        _ServiceLocator.Services.ui.hide('loadVisualization');
      });
      component.observable.on(_Constants.EventTypes.Error, function () {
        _ServiceLocator.Services.ui.reportError((0, _i18n.t)('visualization.errors.visualizationNotPossible'));
      });
      component.observable.on(_Constants.EventTypes.EmptySceneError, function () {
        _ServiceLocator.Services.ui.reportError((0, _i18n.t)('visualization.errors.visualizationNotPossible'));
      });

      // in dev mode expose the three object to the window
      if (!(0, _configuration.isProduction)()) {
        window.visualization = component;
      }
      if (component.getScreenshotsSync) {
        this.registerScreenshotsGetter(component.getScreenshotsSync.bind(component));
      }
      if (component.setView) {
        component.setView(_ServiceLocator.Services.store.state.designView.selectedDesignView);
      }
      if (component.update) {
        this.registerUpdateFunction(component.update.bind(component));
        this.update((0, _Selectors2.getConfiguration)(_ServiceLocator.Services.configurator.state));
      }
      if (component.getDrawingContext) {
        this.registerTextureUpdateFunction(this.drawDesignAreasOnTexture.bind(this));
      }
      if (component.toggleCameraLock) {
        this.registerCameraLockFunction(component.toggleCameraLock.bind(component));
      }
      if (component.toggleHitTest) {
        this.registerToggleHitTestFunction(component.toggleHitTest.bind(component));
      }
      var isAdminMode = (0, _configuration.getConf)('adminMode');
      (0, _sendMessage["default"])(component, 'clearViewIfEmpty', !!isAdminMode);
      var state = _ServiceLocator.Services.store.state;
      var visualizationOverlayMode = (0, _Selectors2.visualizationModeCheck)(state).is2DOverlay();
      (0, _sendMessage["default"])(component, 'setOverlayMode', !!visualizationOverlayMode);
      var visualizationOptions = (0, _configuration.getConf)('visualization.options');
      (0, _sendMessage["default"])(component, 'setOptions', visualizationOptions);
      var visualizationOptions3D = (0, _configuration.getConf)('visualization.options3D');
      (0, _sendMessage["default"])(component, 'setOptions3D', visualizationOptions3D);
      this.observable.dispatch(EventTypes.ComponentChange, {
        component: component
      });
      return this;
    }
  }, {
    key: "addAreaHoverHandler",
    value: function addAreaHoverHandler(component) {
      var _this4 = this;
      var isAreaHovered = false;
      var toggleAreaHovered = function toggleAreaHovered(isHovered) {
        if (isAreaHovered !== isHovered && component !== null && component !== void 0 && component.getContainer) {
          isAreaHovered = isHovered;
          component.getContainer().style.cursor = isAreaHovered ? 'pointer' : '';
        }
      };
      component.observable.on(_Constants.EventTypes.HoverIn, function (evt) {
        // get the texture data from the intersection
        var getTextureHit = evt.data.getTextureHit;
        // so we can test if a design area was clicked
        var area = _this4.testTextureIntersection(getTextureHit());
        toggleAreaHovered(!!area);
      });
      component.observable.on(_Constants.EventTypes.HoverOut, function () {
        toggleAreaHovered(false);
      });
    }
  }, {
    key: "disposeComponent",
    value: function disposeComponent() {
      (0, _sendMessage["default"])(this._component, 'dispose');
      this._component = null;
      this.observable.dispatch(EventTypes.ComponentChange, {
        component: null
      });
    }
  }, {
    key: "getComponent",
    value: function getComponent() {
      return this._component;
    }
  }, {
    key: "registerComponentChangeListener",
    value: function registerComponentChangeListener(fn) {
      return this.observable.on(EventTypes.ComponentChange, fn);
    }
  }, {
    key: "registerVisualizationUpdateListener",
    value: function registerVisualizationUpdateListener(fn) {
      this.observable.on(EventTypes.VisualizationUpdate, fn);
    }
  }, {
    key: "update",
    value: function update(configuration) {
      if (this._onUpdateFn) {
        this._onUpdateFn(configuration);
      } else {
        // save it for later if there is no update function registered yet
        this._configuration = configuration;
      }
      return this;
    }
  }, {
    key: "registerUpdateFunction",
    value: function registerUpdateFunction(onUpdateFn) {
      this._onUpdateFn = onUpdateFn;
      // call the update method if there was already a call for it
      if (this._configuration) {
        this.update(this._configuration);
        delete this._configuration;
      }
      return this;
    }
  }, {
    key: "registerCameraLockFunction",
    value: function registerCameraLockFunction(cameraLockFunction) {
      this._cameraLockFunction = cameraLockFunction;
      return this;
    }
  }, {
    key: "registerToggleHitTestFunction",
    value: function registerToggleHitTestFunction(toggleHitTest) {
      this._toggleHitTest = toggleHitTest;
      return this;
    }

    /**
     * Register the getScreenshots function in the service so it can be proxied to others via this instance
     * @param {function} getScreenshotsFn
     */
  }, {
    key: "registerScreenshotsGetter",
    value: function registerScreenshotsGetter(getScreenshotsFn) {
      this._getScreenshotsFn = getScreenshotsFn;
      return this;
    }

    /**
     * Calls the registered getScreenshot function or returns a resolved Promise
     * @param {object} options The options object forwarded the getScreenshot function
     * @returns {*}
     */
  }, {
    key: "getScreenshots",
    value: function () {
      var _getScreenshots = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
        var options,
          screenshots,
          _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] : {};
              screenshots = null;
              if (!this._getScreenshotsFn) {
                _context5.next = 5;
                break;
              }
              _context5.next = 5;
              return this._getScreenshotsFn(function (result) {
                screenshots = result;
              }, options);
            case 5:
              return _context5.abrupt("return", screenshots);
            case 6:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this);
      }));
      function getScreenshots() {
        return _getScreenshots.apply(this, arguments);
      }
      return getScreenshots;
    }()
  }, {
    key: "abortScreenshotting",
    value: function abortScreenshotting() {
      return (0, _sendMessage["default"])(this.getComponent(), 'abortScreenshotting');
    }

    /**
     * Register a callback for the updateTexture method
     * If there was already a texture update call it triggers the callback immediately with the latest argument.
     * @param {function} onUpdateFn
     * @returns {VisualizationService}
     */
  }, {
    key: "registerTextureUpdateFunction",
    value: function registerTextureUpdateFunction(onUpdateFn) {
      this._onTextureUpdateFn = onUpdateFn;
      // call the update method if there was already a call for it
      if (this._textureUpdateRequest) {
        this.updateTexture(this._textureUpdateRequest);
        delete this._textureUpdateRequest;
      }
      return this;
    }

    /**
     * Calls the previously registered texture update function, if there is any
     * Otherwise it stores the argument internally, so it can be used in the registerTextureUpdateFunction method.
     * @param {*} textureUpdateInfo
     */
  }, {
    key: "updateTexture",
    value: function () {
      var _updateTexture = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
        var textureUpdateInfo,
          _args6 = arguments;
        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              textureUpdateInfo = _args6.length > 0 && _args6[0] !== undefined ? _args6[0] : {};
              if (!this._onTextureUpdateFn) {
                _context6.next = 6;
                break;
              }
              _context6.next = 4;
              return this._onTextureUpdateFn(textureUpdateInfo);
            case 4:
              _context6.next = 7;
              break;
            case 6:
              // save it for later if there is no update function registered yet
              this._textureUpdateRequest = textureUpdateInfo;
            case 7:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this);
      }));
      function updateTexture() {
        return _updateTexture.apply(this, arguments);
      }
      return updateTexture;
    }()
  }, {
    key: "drawDesignAreasOnTexture",
    value: function () {
      var _drawDesignAreasOnTexture = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref3) {
        var drawingFunction, updateEventObject, getDrawingContext;
        return _regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              drawingFunction = _ref3.drawingFunction, updateEventObject = _ref3.updateEventObject;
              _context7.prev = 1;
              getDrawingContext = this._component.getDrawingContext.bind(this._component);
              _context7.t0 = drawingFunction;
              if (!_context7.t0) {
                _context7.next = 7;
                break;
              }
              _context7.next = 7;
              return drawingFunction(getDrawingContext, updateEventObject);
            case 7:
              _context7.next = 12;
              break;
            case 9:
              _context7.prev = 9;
              _context7.t1 = _context7["catch"](1);
              // eslint-disable-next-line no-console
              console.log('Skipping texture update: drawing context is not available.');
            case 12:
            case "end":
              return _context7.stop();
          }
        }, _callee7, this, [[1, 9]]);
      }));
      function drawDesignAreasOnTexture(_x4) {
        return _drawDesignAreasOnTexture.apply(this, arguments);
      }
      return drawDesignAreasOnTexture;
    }()
  }, {
    key: "disableUserMovement",
    value: function disableUserMovement() {
      if (this._cameraLockFunction) {
        this._cameraLockFunction(true);
      }
    }
  }, {
    key: "enableUserMovement",
    value: function enableUserMovement() {
      if (this._cameraLockFunction) {
        this._cameraLockFunction(false);
      }
    }
  }, {
    key: "restrictUserMovement",
    value: function restrictUserMovement() {
      var _this5 = this;
      var component = this.getComponent();
      if (!component) {
        return;
      }
      var zoomHandler = function zoomHandler(_ref4) {
        var direction = _ref4.data.direction;
        if (direction === 'out') {
          _this5._removeRestrictedUserMovementZoomHandler && _this5._removeRestrictedUserMovementZoomHandler();
          _ServiceLocator.Services.designData.clearDesignAreaSelection();
        }
      };
      component.observable.on(_Constants.EventTypes.Zoomed, zoomHandler);
      this._removeRestrictedUserMovementZoomHandler = function () {
        component.observable.off(_Constants.EventTypes.Zoomed, zoomHandler);
        _this5._removeRestrictedUserMovementZoomHandler = null;
      };
      (0, _sendMessage["default"])(component, 'restrictUserMovement');
    }
  }, {
    key: "freeUserMovement",
    value: function freeUserMovement() {
      this._removeRestrictedUserMovementZoomHandler && this._removeRestrictedUserMovementZoomHandler();
      (0, _sendMessage["default"])(this.getComponent(), 'freeUserMovement');
    }
  }, {
    key: "toggleHitTest",
    value: function toggleHitTest(enabled) {
      if (this._toggleHitTest) {
        this._toggleHitTest(enabled);
      }
    }
  }, {
    key: "initDesignAreaInteraction",
    value: function initDesignAreaInteraction() {
      var configurationMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : (0, _Selectors4.getSelectedConfigurationMode)(_ServiceLocator.Services.store.state);
      this.enableDesignAreaInteraction((0, _Selectors4.isDesignerMode)(configurationMode));
    }
  }, {
    key: "enableDesignAreaInteraction",
    value: function enableDesignAreaInteraction(enable) {
      _ServiceLocator.Services.designData.toggleHighlight(enable);
      _ServiceLocator.Services.visualization.toggleHitTest(enable);
    }

    /**
     * Tests if the point from the given texture intersection point is inside of a design area
     * @param textureIntersectionData
     * @see Three.getIntersection
     * @see Three.getTextureHit
     * @returns {*} The design area that contains the given point if any, false otherwise
     */
  }, {
    key: "testTextureIntersection",
    value: function testTextureIntersection(textureIntersectionData) {
      if (textureIntersectionData) {
        var x = textureIntersectionData.x,
          y = textureIntersectionData.y,
          designAreaIdentifier = textureIntersectionData.designAreaIdentifier,
          currentView = textureIntersectionData.currentView;
        var designAreas = _ServiceLocator.Services.designData.getDesignAreas();

        // If the designAreaIdentifier is provided just try to find it in the list.
        // This can be used in any visualization adapter that maps different materials (with own texture) to
        // each design areas. Currently it is being used in the Three2D adapter.
        if (designAreaIdentifier !== undefined) {
          var designAreaSource = (0, _get["default"])(currentView, 'designAreas') || designAreas;
          var foundArea = (0, _find["default"])(designAreaSource, {
            identifier: designAreaIdentifier
          }) || false;
          if (foundArea && foundArea.position && Object.keys(foundArea.position).length > 0) {
            designAreas = [foundArea];
          } else {
            return foundArea;
          }
        }
        // Otherwise it can be treated as a single texture that contains all the areas combined into one.
        // In this case the visualization adapter cannot give a hint about the clicked area,
        // therefore we have to find it by checking the intersection point falls into any of the area ranges.
        var _iterator = _createForOfIteratorHelper(designAreas),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var area = _step.value;
            var _area$position = area.position,
              aWidth = _area$position.width,
              aHeight = _area$position.height;
            var _reversePointTransfor = reversePointTransform(area.position, x, y),
              tX = _reversePointTransfor.x,
              tY = _reversePointTransfor.y;
            var left = -aWidth / 2;
            var right = left + +aWidth;
            var top = -aHeight / 2;
            var bottom = top + +aHeight;
            if (tX >= left && tX <= right && tY >= top && tY <= bottom) {
              return area;
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }
      return false;
    }
  }]);
  return VisualizationService;
}(_AbstractVisualizationService["default"]);
/**
 * This function was copied from the redhotmagma-configurator-administrationgui project
 * original source: src/Screens/Designer/SubScreens/Visualization/Components/FunDraw.js
 * It transforms the given (x, y) coordinates to a locale coordinate of the given object.
 * FIXME: replace if the function is available as an export of a standalone module
 * @param object
 * @param x
 * @param y
 * @returns {{x: number, y: number}}
 */
var reversePointTransform = exports.reversePointTransform = function reversePointTransform(object, x, y) {
  var _x$y$angle$object = _objectSpread({
      x: 0,
      y: 0,
      angle: 0
    }, object),
    cx = _x$y$angle$object.x,
    cy = _x$y$angle$object.y,
    angle = _x$y$angle$object.angle;
  var ox = x - cx;
  var oy = y - cy;
  var cosAi = Math.cos(-angle);
  var sinAi = Math.sin(-angle);
  return {
    x: ox * cosAi - oy * sinAi,
    y: oy * cosAi + ox * sinAi
  };
};