"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _find = _interopRequireDefault(require("lodash/find"));
var _get = _interopRequireDefault(require("lodash/get"));
var _isEqual = _interopRequireDefault(require("lodash/isEqual"));
var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));
var _first = _interopRequireDefault(require("lodash/first"));
var _i18n = require("../../Framework/i18n");
var _Transformers = require("../Modules/Designer/Utils/Transformers");
var _ServiceLocator = require("../ServiceLocator");
var _configuration = require("../configuration");
var _getUrl = require("../Utils/getUrl");
var _Selectors = require("../Reducers/ImageGallery/Selectors");
var _Actions = require("../Reducers/ImageGallery/Actions");
var _Selectors2 = require("../Reducers/DesignArea/Selectors");
var _Selectors3 = require("../Reducers/Fonts/Selectors");
var _Modifiers = require("../Reducers/ImageGallery/Modifiers");
var _Actions2 = require("../Reducers/DesignData/Actions");
var _DesignElementSelectors = require("../Reducers/DesignArea/DesignElementSelectors");
var _FontFaceRepository = require("../Modules/Designer/Utils/FontFaceRepository");
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 _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 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 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 _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function getCanvasImageScalingWithImageData(canvasImage, imageData) {
  var currentPreview = canvasImage.imageData.preview;
  var nextPreview = imageData.preview;
  return canvasImage.scaling * (currentPreview.width / nextPreview.width);
}
function updateCanvasImageWithImageData(canvasImage, imageData) {
  var _imageData$preview$ur;
  return canvasImage.updateOptions((0, _Transformers.prepareImageObjectData)({
    imageData: imageData,
    src: (_imageData$preview$ur = imageData.preview.url) !== null && _imageData$preview$ur !== void 0 && _imageData$preview$ur.startsWith('http') ? imageData.preview.url : "".concat((0, _configuration.getConf)('network.host')).concat(imageData.preview.url),
    scaling: getCanvasImageScalingWithImageData(canvasImage, imageData)
  }));
}
function updateLinkedCanvasImagesWithImageData(imageIdentifier, imageData) {
  _ServiceLocator.Services.store.dispatch((0, _Actions2.updateLinkedImagesWithImageData)(imageIdentifier, imageData));
  return _ServiceLocator.Services.designData.updateCanvasDataFromState();
}
var DesignerService = exports["default"] = /*#__PURE__*/function () {
  function DesignerService() {
    _classCallCheck(this, DesignerService);
    this.imageEditDialogContinueClickHandler = null;
    this.imageEditDialogCloseHandler = null;
  }
  _createClass(DesignerService, [{
    key: "openImageEditDialog",
    value: function () {
      var _openImageEditDialog = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(identifier, canvas) {
        var _this = this;
        var options,
          _options$placeholderI,
          placeholderImageUpdate,
          _options$submitOnExit,
          submitOnExitClick,
          imageEditDialogIdentifier,
          userImages,
          originalImage,
          firstUserImage,
          _args2 = arguments;
        return _regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              options = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : {};
              if (!(!identifier && !this.checkDesignElementRestrictions('image'))) {
                _context2.next = 3;
                break;
              }
              return _context2.abrupt("return");
            case 3:
              _options$placeholderI = options.placeholderImageUpdate, placeholderImageUpdate = _options$placeholderI === void 0 ? false : _options$placeholderI, _options$submitOnExit = options.submitOnExitClick, submitOnExitClick = _options$submitOnExit === void 0 ? false : _options$submitOnExit;
              imageEditDialogIdentifier = 'imageEditDialog';
              userImages = (0, _get["default"])(_ServiceLocator.Services.store.state, 'imageGallery.userImages', []);
              originalImage = identifier && (0, _find["default"])(userImages, {
                identifier: identifier
              }) || null;
              if (originalImage) {
                _ServiceLocator.Services.store.dispatch((0, _Actions.setSelectedImageByIdentifier)(identifier));
                _ServiceLocator.Services.store.dispatch((0, _Actions.setModeToEdit)());
              } else {
                firstUserImage = (0, _first["default"])(userImages);
                firstUserImage && !firstUserImage.isPlaceHolderImage ? _ServiceLocator.Services.store.dispatch((0, _Actions.setSelectedImageByIdentifier)(firstUserImage.identifier)) : _ServiceLocator.Services.store.dispatch((0, _Actions.setSelectedImageByIdentifier)(null));
                _ServiceLocator.Services.store.dispatch((0, _Actions.setModeToAdd)());
              }
              this.imageEditDialogContinueClickHandler = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
                var editMode, updatePosition, placeholderImageObject, image;
                return _regeneratorRuntime().wrap(function _callee$(_context) {
                  while (1) switch (_context.prev = _context.next) {
                    case 0:
                      editMode = (0, _Selectors.isEditMode)(_ServiceLocator.Services.store.state);
                      updatePosition = false;
                      if (!(editMode && !placeholderImageUpdate && !canvas.selectedObject)) {
                        _context.next = 4;
                        break;
                      }
                      throw new Error('imageEditDialogContinueClickHandler must be called in edit mode while either there is an active canvas object or placeholderImageUpdate is true');
                    case 4:
                      if ((0, _Selectors.isColorPreviewCompatible)(_ServiceLocator.Services.store.state)) {
                        _context.next = 6;
                        break;
                      }
                      return _context.abrupt("return");
                    case 6:
                      if (placeholderImageUpdate && (0, _Selectors2.hasPlaceHolderImagesForActiveDesignArea)(_ServiceLocator.Services.store.state)) {
                        placeholderImageObject = canvas.objects.find(function (obj) {
                          return obj.type === 'Image' && obj.imageData.isPlaceHolderImage;
                        });
                        updatePosition = {
                          x: placeholderImageObject.x,
                          y: placeholderImageObject.y
                        };
                        placeholderImageObject && placeholderImageObject.remove();
                      }
                      _ServiceLocator.Services.designData.commitChanges();
                      image = _ServiceLocator.Services.store.state.imageGallery.selectedImage;
                      _context.next = 11;
                      return _ServiceLocator.Services.designData.editFile(_objectSpread({}, image.operations), image, {
                        immediateCommit: true
                      });
                    case 11:
                      if (!(editMode && canvas.selectedObject)) {
                        _context.next = 21;
                        break;
                      }
                      if (!(originalImage && !(0, _Selectors.isHardModified)(image, originalImage))) {
                        _context.next = 17;
                        break;
                      }
                      _context.next = 15;
                      return updateLinkedCanvasImagesWithImageData(originalImage.identifier, image);
                    case 15:
                      _context.next = 19;
                      break;
                    case 17:
                      _context.next = 19;
                      return updateCanvasImageWithImageData(canvas.selectedObject, image);
                    case 19:
                      _context.next = 23;
                      break;
                    case 21:
                      _context.next = 23;
                      return _this.addImageFromUrl(canvas, (0, _Selectors.getPreviewUrlFromImageData)(image.preview), image, {
                        updatePosition: updatePosition
                      });
                    case 23:
                      _ServiceLocator.Services.ui.hide(imageEditDialogIdentifier);
                    case 24:
                    case "end":
                      return _context.stop();
                  }
                }, _callee);
              }));
              this.imageEditDialogCloseHandler = submitOnExitClick ? this.imageEditDialogContinueClickHandler : function () {
                var selectedImage = _ServiceLocator.Services.store.state.imageGallery.selectedImage;
                if (selectedImage && originalImage && selectedImage.identifier === originalImage.identifier && !(0, _isEqual["default"])(selectedImage.operations, originalImage.operations)) {
                  _ServiceLocator.Services.designData.editFile(originalImage.operations, selectedImage, {
                    immediateCommit: true
                  });
                }
                _ServiceLocator.Services.ui.hide(imageEditDialogIdentifier);
              };
              _context2.next = 12;
              return Promise.all([!_ServiceLocator.Services.store.state.imageGallery.tags.length && this.loadTags(), !_ServiceLocator.Services.store.state.imageGallery.gallery.length && this.loadImages()]);
            case 12:
              _ServiceLocator.Services.ui.show(imageEditDialogIdentifier);
            case 13:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function openImageEditDialog(_x, _x2) {
        return _openImageEditDialog.apply(this, arguments);
      }
      return openImageEditDialog;
    }()
  }, {
    key: "loadTags",
    value: function () {
      var _loadTags = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
        return _regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              _context3.next = 2;
              return _ServiceLocator.Services.store.dispatch((0, _Actions.fetchTags)());
            case 2:
              return _context3.abrupt("return", _context3.sent);
            case 3:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }));
      function loadTags() {
        return _loadTags.apply(this, arguments);
      }
      return loadTags;
    }()
  }, {
    key: "loadImages",
    value: function () {
      var _loadImages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return _ServiceLocator.Services.store.dispatch((0, _Actions.fetchGallery)());
            case 2:
              return _context4.abrupt("return", _context4.sent);
            case 3:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }));
      function loadImages() {
        return _loadImages.apply(this, arguments);
      }
      return loadImages;
    }()
  }, {
    key: "uploadFile",
    value: function () {
      var _uploadFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(file) {
        var timeout, response, url, term;
        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              _context5.next = 2;
              return _ServiceLocator.Services.store.dispatch((0, _Actions.setSelectedImageByIdentifier)(null));
            case 2:
              timeout = setTimeout(function () {
                _ServiceLocator.Services.store.dispatch((0, _Actions.updateUploadDelayed)(true));
              }, 10000);
              _context5.next = 5;
              return _ServiceLocator.Services.store.dispatch((0, _Actions.uploadImage)(file));
            case 5:
              response = _context5.sent;
              clearTimeout(timeout);
              url = (0, _get["default"])(response, 'data.preview.url');
              term = (0, _get["default"])(response, 'data.message');
              if (term) {
                _ServiceLocator.Services.ui.alertMessage((0, _i18n.t)(term));
              }
              if (url) {
                _context5.next = 12;
                break;
              }
              throw new Error('Preview image url is not specified!');
            case 12:
              _ServiceLocator.Services.store.dispatch((0, _Actions.updateUploadDelayed)(false));
              return _context5.abrupt("return", (0, _getUrl.getUrl)(url));
            case 14:
            case "end":
              return _context5.stop();
          }
        }, _callee5);
      }));
      function uploadFile(_x3) {
        return _uploadFile.apply(this, arguments);
      }
      return uploadFile;
    }()
  }, {
    key: "addImageFromUrl",
    value: function () {
      var _addImageFromUrl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(canvas, url, imageData) {
        var options,
          _options$enlargeImage,
          enlargeImage,
          _options$updatePositi,
          updatePosition,
          _options$scaleToHalf,
          scaleToHalf,
          _options$autoSelect,
          autoSelect,
          locked,
          item,
          _args6 = arguments;
        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              options = _args6.length > 3 && _args6[3] !== undefined ? _args6[3] : {};
              canvas.clearSelection();
              _options$enlargeImage = options.enlargeImage, enlargeImage = _options$enlargeImage === void 0 ? false : _options$enlargeImage, _options$updatePositi = options.updatePosition, updatePosition = _options$updatePositi === void 0 ? false : _options$updatePositi, _options$scaleToHalf = options.scaleToHalf, scaleToHalf = _options$scaleToHalf === void 0 ? true : _options$scaleToHalf, _options$autoSelect = options.autoSelect, autoSelect = _options$autoSelect === void 0 ? true : _options$autoSelect;
              locked = (0, _Selectors2.getElementLockState)(_ServiceLocator.Services.store.state);
              _context6.next = 6;
              return canvas.addImage((0, _Transformers.prepareObjectData)({
                src: url,
                imageData: imageData,
                locked: locked,
                autoFit: locked
              }));
            case 6:
              item = _context6.sent;
              item.selected = !!autoSelect;
              item.fitCanvas(enlargeImage);
              if (scaleToHalf && item.scaling !== 1) {
                item.scaling *= 0.5;
              }
              if (updatePosition) {
                item.x = updatePosition.x;
                item.y = updatePosition.y;
              }
            case 11:
            case "end":
              return _context6.stop();
          }
        }, _callee6);
      }));
      function addImageFromUrl(_x4, _x5, _x6) {
        return _addImageFromUrl.apply(this, arguments);
      }
      return addImageFromUrl;
    }()
  }, {
    key: "addText",
    value: function () {
      var _addText = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(canvas) {
        var textContent,
          autoColorCount,
          options,
          state,
          _options$fontSizeMin,
          fontSizeMin,
          _options$locked,
          locked,
          _options$fontItem,
          fontItem,
          _options$htmlContent,
          htmlContent,
          _options$fitCanvas,
          fitCanvas,
          text,
          _args7 = arguments;
        return _regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              textContent = _args7.length > 1 && _args7[1] !== undefined ? _args7[1] : 'My Text';
              autoColorCount = _args7.length > 2 && _args7[2] !== undefined ? _args7[2] : 1;
              options = _args7.length > 3 && _args7[3] !== undefined ? _args7[3] : {};
              if (this.checkDesignElementRestrictions('text')) {
                _context7.next = 5;
                break;
              }
              return _context7.abrupt("return");
            case 5:
              canvas.clearSelection();
              state = _ServiceLocator.Services.store.state;
              _options$fontSizeMin = options.fontSizeMin, fontSizeMin = _options$fontSizeMin === void 0 ? (0, _Selectors2.getFontSizeMin)(state) : _options$fontSizeMin, _options$locked = options.locked, locked = _options$locked === void 0 ? (0, _Selectors2.getElementLockState)(state) : _options$locked, _options$fontItem = options.fontItem, fontItem = _options$fontItem === void 0 ? (0, _find["default"])(state.fonts, {
                isDefault: true
              }) || state.fonts[0] : _options$fontItem, _options$htmlContent = options.htmlContent, htmlContent = _options$htmlContent === void 0 ? this.createColorizedTextContent(textContent, autoColorCount) : _options$htmlContent, _options$fitCanvas = options.fitCanvas, fitCanvas = _options$fitCanvas === void 0 ? true : _options$fitCanvas;
              if (fontItem) {
                _context7.next = 12;
                break;
              }
              _ServiceLocator.Services.ui.reportError((0, _i18n.t)('common.noFontsAvailable'));
              _context7.next = 17;
              break;
            case 12:
              _context7.next = 14;
              return _FontFaceRepository.FontFaceRepository.collectFromHTML(htmlContent);
            case 14:
              text = canvas.addText({
                content: htmlContent,
                fontSize: 16,
                fontSizeMin: fontSizeMin,
                fontItem: fontItem,
                locked: locked,
                autoFit: locked
              });
              text.selected = true;
              if (!locked && fitCanvas) {
                this.fitTextToCanvas(text);
              }
            case 17:
            case "end":
              return _context7.stop();
          }
        }, _callee7, this);
      }));
      function addText(_x7) {
        return _addText.apply(this, arguments);
      }
      return addText;
    }()
  }, {
    key: "fitTextToCanvas",
    value: function fitTextToCanvas(text) {
      var canvas = text.canvas;
      text.alignTo('center', 'center');
      text.fontSize = Math.max(text.fontSizeMin, Math.min(canvas.size.width, canvas.size.height) * 0.4);
      if (text.fontSize > text.fontSizeMin && text.getScaledSize().width > canvas.size.width) {
        text.fitCanvas();
      }
    }
  }, {
    key: "checkDesignElementRestrictions",
    value: function checkDesignElementRestrictions(targetElementType) {
      var state = _ServiceLocator.Services.store.state;
      var designData = (0, _Selectors2.getDesignDataForSelectedDesignArea)(state);
      var designProductionMethod = (0, _Selectors2.getSelectedDesignProductionMethod)(state);
      var result = (0, _DesignElementSelectors.checkDesignElementRestrictions)(designData, designProductionMethod, targetElementType);
      if (result) {
        _ServiceLocator.Services.ui.reportError((0, _i18n.t)("designElementRestrictions.addElementMessages.".concat(result.type).concat(result.max === 1 ? '_1' : ''), result));
        return false;
      }
      return true;
    }

    /**
     * @param {string} str
     * @param {number} [colorCount=1]
     * @param {object} [options={}]
     * @returns {string}
     */
  }, {
    key: "createColorizedTextContent",
    value: function createColorizedTextContent(str) {
      var colorCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      var _options$withPlacehol = options.withPlaceholder,
        withPlaceholder = _options$withPlacehol === void 0 ? true : _options$withPlacehol;
      var state = _ServiceLocator.Services.store.state;
      var fontParams = (0, _Selectors3.getDefaultFontParams)(state);
      var chunkLength = Math.ceil(str.length / colorCount);
      var content = str.match(new RegExp(".{1,".concat(chunkLength, "}"), 'g')).map(function (chunk, idx) {
        var color = (0, _Selectors2.getDefaultTextColor)(state, colorCount > 1 ? idx : null);
        var lastImageColor = (0, _Selectors2.getVectorizedImageColor)(state);
        var colorData = (0, _isEmpty["default"])(lastImageColor) ? (0, _Selectors2.createColorData)(color.identifier, color.paletteIdentifier, color.custom, color.value) : lastImageColor;
        return "<span style='color: ".concat(colorData.value, "; ").concat(fontParams, "' data-color='").concat(colorData.identifier, "'>").concat(chunk, "</span>");
      }).join('');
      return withPlaceholder ? (0, _Modifiers.createTextPlaceholder)(content) : content;
    }
  }]);
  return DesignerService;
}();
_defineProperty(DesignerService, "serviceName", 'DesignerService');