"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.ImageEditDialogContainer = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _get = _interopRequireDefault(require("lodash/get"));
var _isEqual = _interopRequireDefault(require("lodash/isEqual"));
var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));
var _size = _interopRequireDefault(require("lodash/size"));
var _isMatch = _interopRequireDefault(require("lodash/isMatch"));
var _ComponentContainer = _interopRequireDefault(require("../../../../Framework/ComponentContainer"));
var _i18n = require("../../../../Framework/i18n");
var _ServiceLocator = require("../../../ServiceLocator");
var _Selectors = require("../../../Reducers/DesignArea/Selectors");
var _Selectors2 = require("../../../Reducers/DesignData/Selectors");
var _Selectors3 = require("../../../Reducers/ImageGallery/Selectors");
var _Selectors4 = require("../../../Reducers/UI/Selectors");
var _Actions = require("../../../Reducers/ImageGallery/Actions");
var _ImageEditDialog = _interopRequireDefault(require("../Components/ImageEditDialog"));
var _ImageUpload = _interopRequireDefault(require("../Components/ImageEditDialog/ImageUpload"));
var _ImageColorize = _interopRequireDefault(require("../Components/ImageColorize"));
var _FeedbackNotice = _interopRequireDefault(require("../Components/FeedbackNotice"));
var _Progress = _interopRequireDefault(require("../../../Shared/Components/Progress/Progress"));
var _DesignDataService = require("../../../Services/DesignDataService");
var _AddGalleryImage = _interopRequireDefault(require("./AddGalleryImage"));
var _createSelector = _interopRequireDefault(require("../../../../Utils/Function/createSelector"));
var _configuration = require("../../../configuration");
var _getUrl = require("../../../Utils/getUrl");
var _Constant = require("../../../Constant");
var _ImageEditUtils = require("../Utils/ImageEditUtils");
var _Transformers = require("../Utils/Transformers");
var _Selectors5 = require("../../../Reducers/Configurator/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 _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
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 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 _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 _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 getOperationsFromState = function getOperationsFromState(state) {
  var clipping = state.clipping,
    clippingColor = state.clippingColor,
    vectorize = state.vectorize,
    vectorizeThreshold = state.vectorizeThreshold,
    vectorizeColorsMap = state.vectorizeColorsMap;
  return {
    clipping: clipping,
    clippingColor: clippingColor,
    vectorize: vectorize,
    vectorizeThreshold: vectorizeThreshold,
    vectorizeColorsMap: vectorizeColorsMap
  };
};
var getLoadingState = (0, _Selectors4.createBackgroundWorkStateSelector)(_Actions.WN_UPLOAD_IMAGE);
var isVectorizableGalleryImage = function isVectorizableGalleryImage(imageData) {
  return Boolean(imageData && !(0, _get["default"])(imageData, 'operations.vectorize') && imageData.gallery && (0, _Selectors3.isEditableVectorImage)(imageData.preview));
};
var getDerivedOperationStateFromImageData = function getDerivedOperationStateFromImageData(imageData) {
  return {
    clipping: (0, _get["default"])(imageData, 'operations.clipping', null),
    clippingColor: (0, _get["default"])(imageData, 'operations.clippingColor', null),
    vectorize: !!(0, _get["default"])(imageData, 'operations.vectorize', false),
    vectorizeThreshold: (0, _get["default"])(imageData, 'operations.vectorizeThreshold', 0),
    vectorizeColorsMap: (0, _get["default"])(imageData, 'operations.vectorizeColorsMap', {}),
    vectorizeOriginalColorsMap: (0, _get["default"])(imageData, 'operations.vectorizeOriginalColorsMap', {}),
    vectorizeMaxColorAmount: (0, _get["default"])(imageData, 'operations.vectorizeMaxColorAmount', undefined)
  };
};
var isImageInvalidatedByChange = function isImageInvalidatedByChange(imageData1, imageData2) {
  return ['operations.clipping', 'operations.clippingColor', 'displayColorPreview'].some(function (key) {
    return (0, _get["default"])(imageData1, key, null) !== (0, _get["default"])(imageData2, key, null);
  });
};
var ImageEditDialogContainer = exports.ImageEditDialogContainer = /*#__PURE__*/function (_React$Component) {
  _inherits(ImageEditDialogContainer, _React$Component);
  var _super = _createSuper(ImageEditDialogContainer);
  function ImageEditDialogContainer() {
    var _this;
    _classCallCheck(this, ImageEditDialogContainer);
    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), "colorAmountNoticeRef", /*#__PURE__*/_react["default"].createRef());
    _defineProperty(_assertThisInitialized(_this), "embroideryNoticeRef", /*#__PURE__*/_react["default"].createRef());
    _defineProperty(_assertThisInitialized(_this), "imageUploadRef", /*#__PURE__*/_react["default"].createRef());
    _defineProperty(_assertThisInitialized(_this), "state", {
      preview: null,
      clipping: null,
      clippingColor: null,
      vectorize: false,
      vectorizeThreshold: 0,
      vectorizeMaxColorAmount: undefined,
      vectorizeColorsMap: {},
      vectorizeOriginalColorsMap: {},
      activeTabIndex: 0,
      showAddImagePanel: false,
      colorAmount: 0,
      continueButtonDisabled: false,
      originalImagePreview: null,
      upload: null
    });
    _defineProperty(_assertThisInitialized(_this), "lastImageUpdateData", null);
    _defineProperty(_assertThisInitialized(_this), "updateOriginalPreview", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
      var image, url, previewUrl, isSvg, svgContent, preview;
      return _regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            image = _this.props.image;
            url = (0, _get["default"])(image, 'preview.url', '');
            previewUrl = (0, _getUrl.getUrl)(url);
            isSvg = previewUrl && /\.svg$/.test(previewUrl);
            if (!isSvg) {
              _context.next = 12;
              break;
            }
            _context.next = 7;
            return (0, _DesignDataService.getSvgContent)(previewUrl, true);
          case 7:
            svgContent = _context.sent;
            preview = (0, _DesignDataService.applySvgContentOperations)(image.original, image.preview, null, svgContent);
            _this.setState({
              originalImagePreview: preview
            });
            _context.next = 13;
            break;
          case 12:
            _this.setState({
              originalImagePreview: previewUrl
            });
          case 13:
          case "end":
            return _context.stop();
        }
      }, _callee);
    })));
    _defineProperty(_assertThisInitialized(_this), "setUpload", function (upload) {
      _this.setState({
        upload: upload
      });
    });
    _defineProperty(_assertThisInitialized(_this), "resetDerivedImageState", function () {
      _this.setState(_objectSpread({
        originalImagePreview: null
      }, getDerivedOperationStateFromImageData()));
    });
    _defineProperty(_assertThisInitialized(_this), "changeSelectedBackground", function (value) {
      var partialState = {
        clipping: value
      };
      if (value !== null && _this.state.clippingColor === null) {
        partialState.clippingColor = '#ffffff';
      }

      // remove the threshold value to trigger the re-creation of the color map
      if (_this.state.vectorizeThreshold) {
        partialState.vectorizeThreshold = null;
      }
      _this.handleStateChange(partialState);
    });
    _defineProperty(_assertThisInitialized(_this), "changeColor", function (color) {
      var partialState = {
        clippingColor: color.hex
      };
      if (_this.state.clipping === null) {
        partialState.clipping = 'replace';
      }

      // remove the threshold value to trigger the re-creation of the color map
      if (_this.state.vectorizeThreshold) {
        partialState.vectorizeThreshold = null;
      }
      _this.handleStateChange(partialState);
    });
    _defineProperty(_assertThisInitialized(_this), "handleStateChange", /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(partialState) {
        var options,
          displayColorPreview,
          image,
          nextState,
          operations,
          result,
          vectorizeColorsMap,
          vectorizeThreshold,
          vectorizeMaxColorAmount,
          vectorizeOriginalColorsMap,
          _args2 = arguments;
        return _regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              options = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {};
              displayColorPreview = options.displayColorPreview;
              image = _this.props.image;
              nextState = _objectSpread(_objectSpread({}, _this.state), partialState);
              _this.setState(nextState);
              operations = getOperationsFromState(nextState);
              if (!(!image || (0, _isMatch["default"])(image.operations, operations) && image.displayColorPreview === displayColorPreview)) {
                _context2.next = 8;
                break;
              }
              return _context2.abrupt("return");
            case 8:
              _this.continueBlocked = true;
              _context2.prev = 9;
              _context2.next = 12;
              return _this.props.editFile(operations, image, displayColorPreview !== undefined && {
                displayColorPreview: displayColorPreview
              });
            case 12:
              result = _context2.sent;
              vectorizeColorsMap = result.vectorizeColorsMap, vectorizeThreshold = result.vectorizeThreshold, vectorizeMaxColorAmount = result.vectorizeMaxColorAmount, vectorizeOriginalColorsMap = result.vectorizeOriginalColorsMap;
              _this.setState({
                vectorizeColorsMap: vectorizeColorsMap,
                vectorizeThreshold: vectorizeThreshold,
                vectorizeMaxColorAmount: vectorizeMaxColorAmount,
                vectorizeOriginalColorsMap: vectorizeOriginalColorsMap
              });
            case 15:
              _context2.prev = 15;
              _this.continueBlocked = false;
              return _context2.finish(15);
            case 18:
            case "end":
              return _context2.stop();
          }
        }, _callee2, null, [[9,, 15, 18]]);
      }));
      return function (_x) {
        return _ref2.apply(this, arguments);
      };
    }());
    _defineProperty(_assertThisInitialized(_this), "onVectorizeToggleChange", function (value) {
      _this.handleStateChange({
        vectorize: value
      });
    });
    _defineProperty(_assertThisInitialized(_this), "onVectorizeThresholdChange", function (threshold) {
      var image = _this.props.image;

      // skip if the threshold is the same as the color count
      var colorCount = (0, _Selectors2.getAggregatedColorCount)(_this.state.vectorizeColorsMap);
      if (threshold === colorCount) {
        return;
      }
      if (threshold !== _this.state.vectorizeThreshold && !image.gallery) {
        return _this.handleStateChange({
          vectorizeThreshold: threshold
        });
      }

      // if the threshold value is the same, there might be some aggregated colors to restore
      return _this.handleStateChange(_objectSpread({
        vectorizeColorsMap: (0, _ImageEditUtils.expandVectorizeColorsMap)(_this.state.vectorizeColorsMap, _this.props.colorPalettes, threshold)
      }, image.gallery && {
        vectorizeThreshold: threshold
      }));
    });
    _defineProperty(_assertThisInitialized(_this), "onColorImageStateReset", /*#__PURE__*/_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 _this.props.resetColorizing();
          case 2:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    })));
    _defineProperty(_assertThisInitialized(_this), "selectColor", /*#__PURE__*/function () {
      var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(colorKey, newColor) {
        var vectorizeColorsMap, colorKeys, _colorKey, _iterator, _step, _colorKey2;
        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              vectorizeColorsMap = (0, _cloneDeep["default"])(_this.state.vectorizeColorsMap);
              colorKeys = (0, _Selectors2.getColorKeysForAggregatedColor)(vectorizeColorsMap, colorKey);
              if (!_ServiceLocator.Services.designData.changeAllColorsNeeded()) {
                _context4.next = 13;
                break;
              }
              _context4.t0 = _regeneratorRuntime().keys(vectorizeColorsMap);
            case 4:
              if ((_context4.t1 = _context4.t0()).done) {
                _context4.next = 11;
                break;
              }
              _colorKey = _context4.t1.value;
              if (vectorizeColorsMap.hasOwnProperty(_colorKey)) {
                _context4.next = 8;
                break;
              }
              return _context4.abrupt("continue", 4);
            case 8:
              vectorizeColorsMap[_colorKey] = newColor;
              _context4.next = 4;
              break;
            case 11:
              _context4.next = 15;
              break;
            case 13:
              _iterator = _createForOfIteratorHelper(colorKeys);
              try {
                for (_iterator.s(); !(_step = _iterator.n()).done;) {
                  _colorKey2 = _step.value;
                  vectorizeColorsMap[_colorKey2] = _objectSpread(_objectSpread({}, newColor), {}, {
                    isUserColor: true
                  });
                }
              } catch (err) {
                _iterator.e(err);
              } finally {
                _iterator.f();
              }
            case 15:
              _context4.next = 17;
              return _this.handleStateChange({
                vectorizeColorsMap: vectorizeColorsMap
              });
            case 17:
              _ServiceLocator.Services.designData.setImageAndTextColor(newColor);
              _ServiceLocator.Services.analytics.triggerEvent(_Constant.EventTypes.image_edit_colorize_color, newColor.value.replace('#', ''));
            case 19:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }));
      return function (_x2, _x3) {
        return _ref4.apply(this, arguments);
      };
    }());
    _defineProperty(_assertThisInitialized(_this), "removeColor", /*#__PURE__*/function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(colorKey) {
        var vectorizeColorsMap, closestColor;
        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              vectorizeColorsMap = _this.state.vectorizeColorsMap;
              if (vectorizeColorsMap[colorKey]) {
                _context5.next = 3;
                break;
              }
              throw new Error('Color key does not exist!');
            case 3:
              closestColor = (0, _ImageEditUtils.getClosestColorFromMap)(vectorizeColorsMap, vectorizeColorsMap[colorKey].value);
              _context5.next = 6;
              return _this.selectColor(colorKey, closestColor);
            case 6:
            case "end":
              return _context5.stop();
          }
        }, _callee5);
      }));
      return function (_x4) {
        return _ref5.apply(this, arguments);
      };
    }());
    _defineProperty(_assertThisInitialized(_this), "onActiveTabChange", function (activeTabIndex) {
      var image = _this.props.image;
      var upload = _this.state.upload;
      if (upload !== null) {
        return;
      }
      if (!image && [1, 2].indexOf(activeTabIndex) !== -1) {
        return;
      }
      _this.setState({
        activeTabIndex: activeTabIndex
      });
    });
    _defineProperty(_assertThisInitialized(_this), "updatePreview", /*#__PURE__*/function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(svgContent) {
        var _image$preview;
        var options,
          _options$forceFetch,
          forceFetch,
          image,
          preview,
          originalImagePreview,
          previewUrl,
          isSvg,
          updateSVG,
          forceUpdate,
          _args6 = arguments;
        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              options = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {};
              _options$forceFetch = options.forceFetch, forceFetch = _options$forceFetch === void 0 ? false : _options$forceFetch;
              image = _this.props.image;
              preview = null;
              originalImagePreview = null;
              previewUrl = image === null || image === void 0 || (_image$preview = image.preview) === null || _image$preview === void 0 ? void 0 : _image$preview.url;
              isSvg = previewUrl && /\.svg$/.test(previewUrl);
              if (!image) {
                _context6.next = 20;
                break;
              }
              updateSVG = isSvg;
              if (!updateSVG) {
                _context6.next = 17;
                break;
              }
              if (svgContent) {
                _context6.next = 14;
                break;
              }
              _context6.next = 13;
              return (0, _DesignDataService.getSvgContent)(image.preview.url, image.preview.url.startsWith('http'), forceFetch);
            case 13:
              svgContent = _context6.sent;
            case 14:
              preview = (0, _DesignDataService.applySvgContentOperations)(image.original, image.preview, image.displayColorPreview ? image.operations : null, svgContent);
              _context6.next = 20;
              break;
            case 17:
              forceUpdate = isImageInvalidatedByChange(_this.lastImageUpdateData, image);
              if (forceUpdate) {
                _this.previewVersion = Math.random();
              }
              if (previewUrl) {
                preview = (0, _Selectors3.getPreviewUrlFromImageData)(previewUrl) + (_this.previewVersion ? "?".concat(_this.previewVersion) : '');
                originalImagePreview = preview;
              }
            case 20:
              _this.lastImageUpdateData = image;
              _this.setState({
                preview: preview,
                originalImagePreview: originalImagePreview
              });
            case 22:
            case "end":
              return _context6.stop();
          }
        }, _callee6);
      }));
      return function (_x5) {
        return _ref6.apply(this, arguments);
      };
    }());
    _defineProperty(_assertThisInitialized(_this), "closeAddImagePanel", function () {
      return _this.setState({
        showAddImagePanel: false
      });
    });
    _defineProperty(_assertThisInitialized(_this), "onSelectImage", /*#__PURE__*/function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(file) {
        var addGalleryImageToUserImages, imageUrl, thumbUrl, fileName, vectorizeColorsMap, svgImageSize;
        return _regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              addGalleryImageToUserImages = _this.props.addGalleryImageToUserImages;
              imageUrl = file.imageUrl, thumbUrl = file.thumbUrl;
              fileName = imageUrl.replace(/^.*[\\/]/, '') // get filename
              .replace(/\.[^.$]+$/, ''); // remove extension
              _context7.next = 5;
              return _ServiceLocator.Services.designData.getGalleryImageColors(imageUrl);
            case 5:
              vectorizeColorsMap = _context7.sent;
              _context7.next = 8;
              return _ServiceLocator.Services.designData.getSVGImageSize(imageUrl);
            case 8:
              svgImageSize = _context7.sent;
              addGalleryImageToUserImages(imageUrl, thumbUrl, fileName, vectorizeColorsMap, svgImageSize);

              // exit image upload if a gallery image is selected
              _this.setUpload(null);
            case 11:
            case "end":
              return _context7.stop();
          }
        }, _callee7);
      }));
      return function (_x6) {
        return _ref7.apply(this, arguments);
      };
    }());
    _defineProperty(_assertThisInitialized(_this), "continueClick", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
      var _this$props, colorDisabled, image, shouldAddImageImmediately, colorPreviewRequirementFulfilled, _this$state, activeTabIndex, continueButtonDisabled;
      return _regeneratorRuntime().wrap(function _callee8$(_context8) {
        while (1) switch (_context8.prev = _context8.next) {
          case 0:
            if (!_this.continueBlocked) {
              _context8.next = 2;
              break;
            }
            return _context8.abrupt("return");
          case 2:
            _this$props = _this.props, colorDisabled = _this$props.colorDisabled, image = _this$props.image, shouldAddImageImmediately = _this$props.shouldAddImageImmediately, colorPreviewRequirementFulfilled = _this$props.colorPreviewRequirementFulfilled;
            _this$state = _this.state, activeTabIndex = _this$state.activeTabIndex, continueButtonDisabled = _this$state.continueButtonDisabled;
            if (!(activeTabIndex === 0 && shouldAddImageImmediately(image))) {
              _context8.next = 13;
              break;
            }
            _this.continueBlocked = true;
            _context8.prev = 6;
            _context8.next = 9;
            return _ServiceLocator.Services.designer.imageEditDialogContinueClickHandler();
          case 9:
            _context8.prev = 9;
            _this.continueBlocked = false;
            return _context8.finish(9);
          case 12:
            return _context8.abrupt("return");
          case 13:
            if (!(activeTabIndex === 0 && !(image.gallery && colorDisabled))) {
              _context8.next = 16;
              break;
            }
            _this.setState({
              activeTabIndex: image.gallery ? 2 : 1
            });
            return _context8.abrupt("return");
          case 16:
            if (!(activeTabIndex === 1 && !colorDisabled)) {
              _context8.next = 19;
              break;
            }
            _this.setState({
              activeTabIndex: 2
            });
            return _context8.abrupt("return");
          case 19:
            if (!(activeTabIndex === 2 && !colorPreviewRequirementFulfilled)) {
              _context8.next = 23;
              break;
            }
            if (!(_this.embroideryNoticeRef && _this.embroideryNoticeRef.current)) {
              _context8.next = 23;
              break;
            }
            _this.embroideryNoticeRef.current.scrollIntoView();
            return _context8.abrupt("return");
          case 23:
            if (!continueButtonDisabled) {
              _context8.next = 27;
              break;
            }
            if (!(_this.colorAmountNoticeRef && _this.colorAmountNoticeRef.current)) {
              _context8.next = 27;
              break;
            }
            _this.colorAmountNoticeRef.current.scrollIntoView();
            return _context8.abrupt("return");
          case 27:
            _this.continueBlocked = true;
            _context8.prev = 28;
            _context8.next = 31;
            return _ServiceLocator.Services.designer.imageEditDialogContinueClickHandler();
          case 31:
            _context8.prev = 31;
            _this.continueBlocked = false;
            return _context8.finish(31);
          case 34:
          case "end":
            return _context8.stop();
        }
      }, _callee8, null, [[6,, 9, 12], [28,, 31, 34]]);
    })));
    _defineProperty(_assertThisInitialized(_this), "onGalleryClick", function () {
      _this.setState({
        showAddImagePanel: true
      });
    });
    _defineProperty(_assertThisInitialized(_this), "closePreviewDialog", function () {
      _ServiceLocator.Services.designer.imageEditDialogCloseHandler();
    });
    _defineProperty(_assertThisInitialized(_this), "onOriginalImageAndColorPreviewToggleClick", function () {
      _this.handleStateChange({}, {
        displayColorPreview: !_this.props.displayColorPreview
      });
    });
    _defineProperty(_assertThisInitialized(_this), "uploadImage", function () {
      return _this.imageUploadRef.current.uploadFile();
    });
    _defineProperty(_assertThisInitialized(_this), "onNewUploadClick", function () {
      _this.setUpload({
        disabled: true
      });
      _this.resetDerivedImageState();
    });
    _defineProperty(_assertThisInitialized(_this), "selectUserImage", function (imageIndex) {
      var _this$props2 = _this.props,
        userImages = _this$props2.userImages,
        setSelectedImage = _this$props2.setSelectedImage;
      setSelectedImage(userImages[imageIndex].identifier);
      _this.resetDerivedImageState();
    });
    return _this;
  }
  _createClass(ImageEditDialogContainer, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.updatePreview(null);
      var _this$props3 = this.props,
        image = _this$props3.image,
        editMode = _this$props3.editMode,
        hasPlaceHolderImage = _this$props3.hasPlaceHolderImage,
        colorDisabled = _this$props3.colorDisabled;
      var initialState = getDerivedOperationStateFromImageData(image);
      if (editMode && image && !hasPlaceHolderImage) {
        initialState.activeTabIndex = initialState.vectorize && !colorDisabled ? 2 : 1;
      }
      this.setState(initialState);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      var _this$props4 = this.props,
        image = _this$props4.image,
        open = _this$props4.open,
        maxColorAmount = _this$props4.maxColorAmount,
        editMode = _this$props4.editMode,
        hasPlaceHolderImage = _this$props4.hasPlaceHolderImage,
        isImageCompatible = _this$props4.isImageCompatible,
        isColorMappingCompatible = _this$props4.isColorMappingCompatible,
        vectorsRequired = _this$props4.vectorsRequired,
        vectorizedLogoMandatory = _this$props4.vectorizedLogoMandatory;
      var _this$state2 = this.state,
        vectorize = _this$state2.vectorize,
        vectorizeColorsMap = _this$state2.vectorizeColorsMap,
        activeTabIndex = _this$state2.activeTabIndex,
        originalImagePreview = _this$state2.originalImagePreview;
      var newState = {};
      var justOpened = open !== prevProps.open && open;
      var imageChanged = !!image && image !== prevProps.image;
      var prevOperationData = getDerivedOperationStateFromImageData(prevProps.image);
      var operationData = getDerivedOperationStateFromImageData(image);
      var operationsChanged = !!image && !(0, _isEqual["default"])(prevOperationData, operationData);
      if (image && image.preview && image.preview.url && activeTabIndex === 2 && originalImagePreview === null && !(0, _Transformers.isOriginalVector)(image)) {
        this.updateOriginalPreview();
      }
      if (operationsChanged) {
        Object.assign(newState, operationData);
      }
      if (justOpened) {
        var _activeTabIndex = 0;
        if (image && editMode && !hasPlaceHolderImage) {
          _activeTabIndex = (0, _Selectors3.isEditableVectorImage)(image.preview) ? 2 : 1;
        }
        Object.assign(newState, {
          activeTabIndex: _activeTabIndex
        });
      }
      if (maxColorAmount !== prevProps.maxColorAmount || vectorize !== prevState.vectorize || vectorizeColorsMap !== prevState.vectorizeColorsMap || activeTabIndex !== prevState.activeTabIndex) {
        var colorAmount = (0, _Selectors2.getAggregatedColorCount)(vectorizeColorsMap);
        var continueButtonDisabled = activeTabIndex === 2 && vectorize && !!maxColorAmount && colorAmount > maxColorAmount;
        this.setState({
          colorAmount: colorAmount,
          continueButtonDisabled: continueButtonDisabled
        });
      }
      if (activeTabIndex === 2 && isVectorizableGalleryImage(image) && (!vectorize ||
      // if the user comes from the background removal tab vectorizing should be performed again
      prevState.activeTabIndex === 1)) {
        Object.assign(newState, {
          vectorize: true
        });
      }

      // when switching to the colorizing tab the color has to be made compatible
      if (activeTabIndex === 2 && activeTabIndex !== prevState.activeTabIndex && (!isImageCompatible(image) || !isColorMappingCompatible(vectorizeColorsMap))) {
        Object.assign(newState, {
          vectorizeColorsMap: vectorizeColorsMap
        });
      }
      if (activeTabIndex === 2 && (vectorsRequired || vectorizedLogoMandatory) && !vectorize && !image.gallery) {
        Object.assign(newState, {
          vectorize: true
        });
      }
      var options;
      if (activeTabIndex === 2 && !image.gallery && vectorizedLogoMandatory && !image.displayColorPreview && !this.state.displayColorPreview) {
        options = {
          displayColorPreview: true
        };
        Object.assign(newState, {
          displayColorPreview: true
        });
      }
      (!(0, _isMatch["default"])(this.state, newState) || options) && this.handleStateChange(newState, options);
      if ((justOpened || imageChanged) && !image.incomplete) {
        this.updatePreview(null, {
          forceFetch: operationsChanged
        });
      } else if (activeTabIndex !== prevState.activeTabIndex && vectorize) {
        this.updatePreview(null, {
          forceFetch: true
        });
      }

      // update upload state if it is just opened
      if (justOpened) {
        var _this$props5 = this.props,
          userImages = _this$props5.userImages,
          galleryHasImages = _this$props5.galleryHasImages;
        var upload = null;

        // if no gallery images, default to user upload
        if (!image && !userImages.length && !galleryHasImages) {
          upload = {
            disabled: true
          };
        }
        this.setUpload(upload);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var _this$props6 = this.props,
        loading = _this$props6.loading,
        ProgressComponent = _this$props6.ProgressComponent,
        errorCode = _this$props6.errorCode,
        colorPalettes = _this$props6.colorPalettes,
        maxColorAmount = _this$props6.maxColorAmount,
        colorDisabled = _this$props6.colorDisabled,
        vectorsRequired = _this$props6.vectorsRequired,
        vectorizedLogoMandatory = _this$props6.vectorizedLogoMandatory,
        image = _this$props6.image,
        usedColors = _this$props6.usedColors,
        imageColorsWereEdited = _this$props6.imageColorsWereEdited,
        colorPreviewEnabled = _this$props6.colorPreviewEnabled,
        colorPreviewRequirementFulfilled = _this$props6.colorPreviewRequirementFulfilled,
        uploadSize = _this$props6.uploadSize,
        ImageColorizeComponent = _this$props6.ImageColorizeComponent,
        ImageUploadComponent = _this$props6.ImageUploadComponent,
        customControlElements = _this$props6.customControlElements,
        checkOwnership = _this$props6.checkOwnership,
        designProductionMethod = _this$props6.designProductionMethod,
        client = _this$props6.client,
        uploadDelayed = _this$props6.uploadDelayed,
        loopIcon = _this$props6.loopIcon,
        colorizeIcon = _this$props6.colorizeIcon,
        formatPaintIcon = _this$props6.formatPaintIcon,
        photoLibraryIcon = _this$props6.photoLibraryIcon,
        addIcon = _this$props6.addIcon,
        imageIcon = _this$props6.imageIcon,
        checkIcon = _this$props6.checkIcon,
        errorIcon = _this$props6.errorIcon;
      var _this$state3 = this.state,
        preview = _this$state3.preview,
        clipping = _this$state3.clipping,
        vectorize = _this$state3.vectorize,
        vectorizeColorsMap = _this$state3.vectorizeColorsMap,
        activeTabIndex = _this$state3.activeTabIndex,
        colorAmount = _this$state3.colorAmount,
        continueButtonDisabled = _this$state3.continueButtonDisabled,
        originalImagePreview = _this$state3.originalImagePreview,
        upload = _this$state3.upload;
      var isGalleryImage = image && !!image.gallery;
      var showWarningMessage = (0, _Selectors3.showVectorizeImageQuality)(image);
      var aggregatedColors = (0, _Selectors2.getAggregatedColors)(vectorizeColorsMap);
      var colorAmountList = Array(maxColorAmount).fill(null).map(function (_, i) {
        return i + 1;
      });
      var colorCount = (0, _size["default"])(aggregatedColors);
      var colorPreviewBlockActive = activeTabIndex === 2 && colorCount > 0 && !isGalleryImage && !vectorizedLogoMandatory && (colorPreviewEnabled || !colorPreviewRequirementFulfilled);
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_ImageEditDialog["default"], _extends({}, this.props, {
        loaderComponent: /*#__PURE__*/_react["default"].createElement(ProgressComponent, {
          loading: loading
        }),
        errorFeedback: errorCode && /*#__PURE__*/_react["default"].createElement(_FeedbackNotice["default"], {
          errorNotice: (0, _i18n.t)("fileUpload.errors.".concat(errorCode))
        }),
        changeSelectedBackground: this.changeSelectedBackground,
        onChangeColor: this.changeColor,
        closePreviewDialog: this.closePreviewDialog,
        backgroundSelected: clipping,
        preview: preview,
        uploadDelayed: uploadDelayed,
        continueButtonDisabled: continueButtonDisabled,
        continueClick: this.continueClick,
        showWarningMessage: showWarningMessage,
        imageColorizeElement: /*#__PURE__*/_react["default"].createElement(ImageColorizeComponent, {
          inputRef: this.colorAmountNoticeRef,
          colorPalettes: colorPalettes,
          usedColors: usedColors,
          vectorizeThreshold: colorCount > maxColorAmount ? 0 : colorCount,
          onVectorizeThresholdChange: this.onVectorizeThresholdChange,
          vectorizeColorsMap: vectorizeColorsMap,
          onColorSelectClick: this.selectColor,
          onColorRemoveClick: this.removeColor,
          aggregatedColors: aggregatedColors,
          disableInputs: !vectorize && !isGalleryImage || colorDisabled,
          maxColorAmount: maxColorAmount,
          colorAmount: colorAmount,
          vectorize: vectorize,
          onVectorizeToggleChange: this.onVectorizeToggleChange,
          vectorizeToggleDisabled: vectorsRequired || isGalleryImage && vectorize,
          onColorImageStateReset: this.onColorImageStateReset,
          isLoading: loading,
          imageColorsWereEdited: imageColorsWereEdited,
          vectorsRequired: vectorsRequired,
          colorAmountList: colorAmountList,
          customControlElements: customControlElements,
          designProductionMethodName: designProductionMethod === null || designProductionMethod === void 0 ? void 0 : designProductionMethod.title
        }),
        activeTabIndex: activeTabIndex,
        onActiveTabChange: this.onActiveTabChange,
        onGalleryClick: this.onGalleryClick,
        onOriginalImageAndColorPreviewToggleClick: this.onOriginalImageAndColorPreviewToggleClick,
        originalImagePreview: originalImagePreview,
        embroideryNoticeRef: this.embroideryNoticeRef,
        colorPreviewBlockActive: colorPreviewBlockActive,
        onNewUploadClick: this.onNewUploadClick,
        showUploadPanel: upload !== null,
        uploadDisabled: !!(upload && upload.disabled),
        uploadImage: this.uploadImage,
        selectUserImage: this.selectUserImage,
        imageUploadElement: /*#__PURE__*/_react["default"].createElement(ImageUploadComponent, {
          innerRef: this.imageUploadRef,
          uploadSize: uploadSize,
          onValidate: function onValidate(_ref9) {
            var isValid = _ref9.isValid;
            return _this2.setUpload({
              disabled: !isValid
            });
          },
          onUploadFinished: function onUploadFinished() {
            _this2.setUpload(null);
            _this2.onActiveTabChange(1);
          },
          checkOwnership: checkOwnership,
          imageIcon: imageIcon,
          checkIcon: checkIcon,
          errorIcon: errorIcon,
          loopIcon: loopIcon
        }),
        loopIcon: loopIcon,
        colorizeIcon: colorizeIcon,
        formatPaintIcon: formatPaintIcon,
        photoLibraryIcon: photoLibraryIcon,
        addIcon: addIcon
      })), /*#__PURE__*/_react["default"].createElement(_AddGalleryImage["default"], {
        open: this.state.showAddImagePanel,
        onClose: this.closeAddImagePanel,
        onSelectImage: this.onSelectImage,
        client: client
      }));
    }
  }]);
  return ImageEditDialogContainer;
}(_react["default"].Component);
_defineProperty(ImageEditDialogContainer, "defaultProps", {
  colorPreviewRequirementFulfilled: false,
  colorPreviewEnabled: false,
  checkOwnership: true
});
var getUserImages = (0, _createSelector["default"])(function (imageGalleryState) {
  return imageGalleryState.userImages;
}, function (images) {
  var userImages = images.filter(function (image) {
    return !image.isPlaceHolderImage;
  });
  return userImages.map(function (image) {
    return _objectSpread(_objectSpread({}, image), {}, {
      url: (0, _getUrl.getUrl)(image.thumbnail.url)
    });
  });
});
var mapStateToProps = function mapStateToProps(state) {
  var ui = state.ui,
    imageGallery = state.imageGallery;
  var colorPalettes = (0, _Selectors.getColorPalettes)(state);
  var designProductionMethod = (0, _Selectors.getSelectedDesignProductionMethod)(state);
  var vectorsRequired = !!(0, _get["default"])(designProductionMethod, 'options.vectorsRequired');
  var vectorizedLogoMandatory = !!(0, _get["default"])(designProductionMethod, 'options.vectorizedLogoMandatory');
  var colorDisabled = (0, _Selectors.isColoringDisabled)(state);
  var userImages = getUserImages(imageGallery);
  var hasPlaceHolderImage = (0, _Selectors.hasPlaceHolderImagesForActiveDesignArea)(state);
  var firstUserImageToPreSelect = userImages.length > 0 ? userImages[0] : null;
  var userImage = imageGallery.selectedImage || firstUserImageToPreSelect;
  var defaultMaxColorAmount = (0, _configuration.getConf)('designer.maxColorAmount', 10);
  var maxColorAmount = Math.min(+(0, _get["default"])(designProductionMethod, 'options.maxColorAmount') || defaultMaxColorAmount, +(0, _get["default"])(userImage, 'operations.vectorizeMaxColorAmount', defaultMaxColorAmount));
  var editMode = (0, _Selectors3.isEditMode)(state);
  var galleryHasImages = imageGallery.gallery.length !== 0;
  var uploadSize = (0, _Selectors.getMaxUploadSize)(state);
  var open = !!ui.visibilityMap.imageEditDialog;
  var usedColors = (0, _Selectors.getDesignDataUsedColors)(state);
  var displayColorPreview = userImage && !!userImage.displayColorPreview;
  var colorPreviewEnabled = userImage && !!userImage.colorPreviewEnabled;
  var imageColorsWereEdited = userImage && !!userImage.imageColorsWereEdited;
  var initialColorMaxAmount = (0, _Selectors2.getInitialMaxColorAmount)(state);
  var colorPreviewRequirementFulfilled = (0, _Selectors3.isColorPreviewCompatible)(state, userImage);
  var client = (0, _Selectors5.getClient)((0, _Selectors5.getConfigurator)(state));
  var uploadDelayed = imageGallery.uploadDelayed;
  return {
    Component: open ? ImageEditDialogContainer : function () {
      return null;
    },
    ProgressComponent: _Progress["default"],
    ImageColorizeComponent: _ImageColorize["default"],
    ImageUploadComponent: _ImageUpload["default"],
    errorCode: imageGallery.lastErrorCode,
    loading: getLoadingState(ui) || !!(userImage && userImage.incomplete),
    image: userImage,
    maxColorAmount: maxColorAmount,
    displayColorPreview: displayColorPreview,
    colorPreviewEnabled: colorPreviewEnabled,
    imageColorsWereEdited: imageColorsWereEdited,
    editMode: editMode,
    open: open,
    userImages: userImages,
    colorPalettes: colorPalettes,
    vectorsRequired: vectorsRequired,
    vectorizedLogoMandatory: vectorizedLogoMandatory,
    colorDisabled: colorDisabled,
    uploadSize: uploadSize,
    galleryHasImages: galleryHasImages,
    usedColors: usedColors,
    hasPlaceHolderImage: hasPlaceHolderImage,
    initialColorMaxAmount: initialColorMaxAmount,
    colorPreviewRequirementFulfilled: colorPreviewRequirementFulfilled,
    designProductionMethod: designProductionMethod,
    client: client,
    uploadDelayed: uploadDelayed
  };
};
var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    editFile: function editFile(operations, image) {
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      return _ServiceLocator.Services.designData.editFileQueued(operations, image, _objectSpread({
        addMode: (0, _Selectors3.isAddMode)(_ServiceLocator.Services.store.state)
      }, options));
    },
    setSelectedImage: function setSelectedImage(identifier) {
      return dispatch((0, _Actions.setSelectedImageByIdentifier)(identifier));
    },
    addGalleryImageToUserImages: function addGalleryImageToUserImages(imageUrl, thumbUrl, fileName, vectorizeColorsMap, svgImageSize) {
      return dispatch((0, _Actions.addGalleryImageToUserImages)(imageUrl, thumbUrl, fileName, vectorizeColorsMap, svgImageSize));
    },
    shouldAddImageImmediately: function shouldAddImageImmediately(imageData) {
      return (0, _Selectors3.isImageReadyToBeAdded)(_ServiceLocator.Services.store.state, imageData);
    },
    isColorMappingCompatible: function isColorMappingCompatible(vectorizeColorsMap) {
      return (0, _Selectors3.isColorMappingCompatible)((0, _Selectors.getSelectedDesignProductionMethod)(_ServiceLocator.Services.store.state).colorPalettes, vectorizeColorsMap);
    },
    isImageCompatible: function isImageCompatible(imageData) {
      return (0, _Selectors3.isImageCompatible)(_ServiceLocator.Services.store.state, imageData);
    },
    resetColorizing: function resetColorizing() {
      return _ServiceLocator.Services.designData.resetEditedFile();
    }
  };
};
var _default = exports["default"] = (0, _ComponentContainer["default"])(mapStateToProps, mapDispatchToProps);