"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.setColorOnOperations = exports.replaceColorOnOperations = exports.removeVectorizeFromOperations = exports.reduceNumberOfDistinctColorsBy = exports.isOneColorAboveThreshold = exports.getEditDataFromOperations = exports.extendCanvasDataWithMetricContentSize = exports.createVectorizeColorsMap = exports.compareOperations = exports.applyProductionMethodChangeToCanvasObjects = void 0;
var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));
var _isEqual = _interopRequireDefault(require("lodash/isEqual"));
var _omit = _interopRequireDefault(require("lodash/omit"));
var _find = _interopRequireDefault(require("lodash/find"));
var _flatten = _interopRequireDefault(require("lodash/flatten"));
var _get = _interopRequireDefault(require("lodash/get"));
var _Selectors = require("./Selectors");
var _Selectors2 = require("../DesignArea/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 _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
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 _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 setColorOnOperations = exports.setColorOnOperations = function setColorOnOperations(prevOperations, color) {
  var operations = (0, _cloneDeep["default"])(prevOperations);
  for (var colorKey in operations.vectorizeColorsMap) {
    if (!operations.vectorizeColorsMap.hasOwnProperty(colorKey)) {
      continue;
    }
    operations.vectorizeColorsMap[colorKey] = color;
  }
  return operations;
};
var replaceColorOnOperations = exports.replaceColorOnOperations = function replaceColorOnOperations(prevOperations, oldColor, color) {
  var operations = (0, _cloneDeep["default"])(prevOperations);
  for (var colorKey in operations.vectorizeColorsMap) {
    if (!operations.vectorizeColorsMap.hasOwnProperty(colorKey)) {
      continue;
    }
    if (operations.vectorizeColorsMap[colorKey].identifier === oldColor.identifier) {
      operations.vectorizeColorsMap[colorKey] = color;
    }
  }
  return operations;
};
var getEditDataFromOperations = exports.getEditDataFromOperations = function getEditDataFromOperations(imageFileName, operations, designProductionMethod) {
  var _operations$clipping = operations.clipping,
    clipping = _operations$clipping === void 0 ? false : _operations$clipping,
    _operations$clippingC = operations.clippingColor,
    clippingColor = _operations$clippingC === void 0 ? false : _operations$clippingC,
    _operations$vectorize = operations.vectorize,
    vectorize = _operations$vectorize === void 0 ? false : _operations$vectorize,
    _operations$vectorize2 = operations.vectorizeThreshold,
    vectorizeThreshold = _operations$vectorize2 === void 0 ? null : _operations$vectorize2;
  var maxColorAmount = +(0, _get["default"])(designProductionMethod, 'options.maxColorAmount', 0);
  var vectorizedLogoMandatory = (0, _get["default"])(designProductionMethod, 'options.vectorizedLogoMandatory', false);
  var vectorizeMonochrome = maxColorAmount === 1 && vectorizeThreshold === 1;
  var result = {
    fileName: imageFileName,
    operations: [],
    vectorizedLogoMandatory: vectorizedLogoMandatory
  };
  if (clipping && clippingColor) {
    result.operations.push({
      identifier: 'clipping',
      config: {
        command: clipping,
        backgroundColor: clippingColor
      }
    });
  }
  if (vectorize) {
    result.operations.push({
      identifier: 'vectorize',
      config: {
        threshold: vectorizeThreshold,
        monochrome: vectorizeMonochrome
      }
    });
  }
  return result;
};
var compareOperations = exports.compareOperations = function compareOperations(oldOperations, newOperations) {
  return (0, _isEqual["default"])((0, _omit["default"])(oldOperations, ['vectorizeColorsMap']), (0, _omit["default"])(newOperations, ['vectorizeColorsMap']));
};
var createVectorizeColorsMap = exports.createVectorizeColorsMap = function createVectorizeColorsMap(currentColorsMap, svgColors) {
  // make sure the original color ordering is kept by creating placeholders for the keys
  var vectorizeColorsMap = svgColors.reduce(function (obj, _ref) {
    var key = _ref.key;
    return _objectSpread(_objectSpread({}, obj), {}, _defineProperty({}, key, undefined));
  }, {});
  currentColorsMap && Object.keys(currentColorsMap).forEach(function (key) {
    var oldColor = currentColorsMap[key];
    if (!(0, _find["default"])(svgColors, {
      key: key
    })) {
      return;
    }
    vectorizeColorsMap[key] = oldColor;
  });
  var _iterator = _createForOfIteratorHelper(svgColors),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _step$value = _step.value,
        key = _step$value.key,
        color = _step$value.color;
      if (!vectorizeColorsMap[key]) {
        vectorizeColorsMap[key] = color;
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return vectorizeColorsMap;
};
var isOneColorAboveThreshold = exports.isOneColorAboveThreshold = function isOneColorAboveThreshold(vectorizeColorsMap, vectorizeOriginalColorsMap) {
  var threshold = 1900;
  var aggregatedInitialColors = (0, _Selectors.getAggregatedColors)(vectorizeOriginalColorsMap || {});
  var aggregatedCurrentColors = (0, _Selectors.getAggregatedColors)(vectorizeColorsMap || {});
  if (Object.keys(aggregatedInitialColors).length !== Object.keys(aggregatedCurrentColors).length) {
    return true;
  }
  var numberOfCustomColors = Object.values(aggregatedCurrentColors).filter(function (c) {
    return c.identifier && JSON.parse(c.identifier).custom;
  }).length;
  var numberOfNotMatchingColors = Object.entries(aggregatedInitialColors).reduce(function (accumulator, _ref2) {
    var _ref3 = _slicedToArray(_ref2, 2),
      key = _ref3[0],
      initialColor = _ref3[1];
    var currentColor = Object.values(aggregatedCurrentColors).find(function (c) {
      return c.value === initialColor.value;
    });
    if (currentColor) {
      return accumulator;
    }
    if (!aggregatedCurrentColors[key]) {
      return accumulator + 1;
    }
    var colorDistance = (0, _Selectors2.calculateColorDistance)(initialColor.value, aggregatedCurrentColors[key].value);
    return colorDistance === null || colorDistance > threshold ? accumulator + 1 : accumulator;
  }, 0);
  return numberOfNotMatchingColors > numberOfCustomColors;
};
var removeVectorizeFromOperations = exports.removeVectorizeFromOperations = function removeVectorizeFromOperations(operations) {
  return _objectSpread(_objectSpread({}, operations), {}, {
    vectorize: false,
    vectorizeThreshold: null,
    vectorizeMaxColorAmount: undefined,
    vectorizeColorsMap: {},
    vectorizeOriginalColorsMap: {},
    vectorizeMonochrome: false
  });
};
var getColorKeysForIdentifier = function getColorKeysForIdentifier(vectorizeColorsMap, identifier) {
  return Object.entries(vectorizeColorsMap).filter(function (colorEntry) {
    return colorEntry[1].identifier === identifier;
  }).map(function (colorEntry) {
    return colorEntry[0];
  });
};
var findDistinctIdentifiers = function findDistinctIdentifiers(howMany, vectorizeColorsMap) {
  var distinctIdentifiers = [];
  Object.values(vectorizeColorsMap).forEach(function (colorEntry) {
    if (!distinctIdentifiers.includes(colorEntry.identifier) && distinctIdentifiers.length < howMany) {
      distinctIdentifiers.push(colorEntry.identifier);
    }
  });
  return distinctIdentifiers;
};
var reduceNumberOfDistinctColorsBy = exports.reduceNumberOfDistinctColorsBy = function reduceNumberOfDistinctColorsBy(vectorizeColorsMap, numberOfColorsToRemove) {
  var numberOfUniqueColorValues = Object.values(vectorizeColorsMap).map(function (c) {
    return c.identifier;
  }).filter(function (c, index, array) {
    return array.indexOf(c) === index;
  }).length;
  if (numberOfUniqueColorValues <= numberOfColorsToRemove) {
    throw new Error('vectorizeColorsMap must have more unique colors than the number of colors we are reducing it by');
  }
  var identifiers = findDistinctIdentifiers(numberOfColorsToRemove, vectorizeColorsMap);
  var keysForValuesToBeOverWritten = (0, _flatten["default"])(identifiers.map(function (identifier) {
    return getColorKeysForIdentifier(vectorizeColorsMap, identifier);
  }));
  var sourceColorValue = Object.entries(vectorizeColorsMap).find(function (colorEntry) {
    return !keysForValuesToBeOverWritten.includes(colorEntry[0]);
  })[1];
  var resultingVecotirzeColorsMap = {};
  var _loop = function _loop(key) {
    if (keysForValuesToBeOverWritten.find(function (k) {
      return k === key;
    })) {
      resultingVecotirzeColorsMap[key] = sourceColorValue;
    } else {
      resultingVecotirzeColorsMap[key] = vectorizeColorsMap[key];
    }
  };
  for (var key in vectorizeColorsMap) {
    _loop(key);
  }
  return resultingVecotirzeColorsMap;
};
var applyProductionMethodChangeToCanvasObjects = exports.applyProductionMethodChangeToCanvasObjects = function applyProductionMethodChangeToCanvasObjects(newProductionMethod, oldProductionMethod, objects) {
  return [updatePositioningAndScaling, updateLockState].reduce(function (objects, updateFunc) {
    return updateFunc(newProductionMethod, oldProductionMethod, objects);
  }, objects);
};
var updatePositioningAndScaling = function updatePositioningAndScaling(newProductionMethod, oldProductionMethod, objects) {
  var widthA = newProductionMethod.width,
    heightA = newProductionMethod.height;
  var widthB = oldProductionMethod.width,
    heightB = oldProductionMethod.height;
  if (widthA !== widthB || heightA !== heightB) {
    var scaleX = widthA / widthB;
    var scaleY = heightA / heightB;
    return objects.map(function (object) {
      var x = object.x,
        y = object.y;
      var fixedObject = _objectSpread(_objectSpread({}, object), {}, {
        x: x * scaleX,
        y: y * scaleY
      });
      if (fixedObject.fontSize) {
        fixedObject.fontSize *= scaleY;
      }
      return fixedObject;
    });
  }
  return objects;
};
var updateLockState = function updateLockState(newProductionMethod, oldProductionMethod, objects) {
  var lockedA = newProductionMethod.designElementsLocked;
  var lockedB = oldProductionMethod.designElementsLocked;
  if (lockedA !== lockedB) {
    return objects.map(function (object) {
      return _objectSpread(_objectSpread({}, object), {}, {
        rotation: 0,
        autoFit: lockedA,
        locked: lockedA
      });
    });
  }
  return objects;
};
var extendCanvasDataWithMetricContentSize = exports.extendCanvasDataWithMetricContentSize = function extendCanvasDataWithMetricContentSize(canvasData) {
  var b = {
    minX: Infinity,
    maxX: -Infinity,
    minY: Infinity,
    maxY: -Infinity
  };
  var mergeRotated = function mergeRotated(cx, cy, hw, hh, deg) {
    var rad = deg * Math.PI / 180;
    var c = Math.cos(rad);
    var s = Math.sin(rad);
    for (var _i = 0, _arr = [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]]; _i < _arr.length; _i++) {
      var _arr$_i = _slicedToArray(_arr[_i], 2),
        dx = _arr$_i[0],
        dy = _arr$_i[1];
      var x = cx + dx * c - dy * s;
      var y = cy + dx * s + dy * c;
      b.minX = Math.min(b.minX, x);
      b.maxX = Math.max(b.maxX, x);
      b.minY = Math.min(b.minY, y);
      b.maxY = Math.max(b.maxY, y);
    }
  };
  var mergeAxisAligned = function mergeAxisAligned(cx, cy, hw, hh) {
    b.minX = Math.min(b.minX, cx - hw);
    b.maxX = Math.max(b.maxX, cx + hw);
    b.minY = Math.min(b.minY, cy - hh);
    b.maxY = Math.max(b.maxY, cy + hh);
  };
  var _iterator2 = _createForOfIteratorHelper(canvasData.objects),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var object = _step2.value;
      if (!object.metric) continue;
      var w = object.metric.width || 0;
      var h = object.metric.height || 0;
      var hw = w / 2;
      var hh = h / 2;
      var cx = object.metric.x || 0;
      var cy = object.metric.y || 0;
      if (typeof object.rotation === 'number' && object.rotation !== 0 && w && h) {
        mergeRotated(cx, cy, hw, hh, object.rotation);
      } else {
        mergeAxisAligned(cx, cy, hw, hh);
      }
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  if (!Number.isFinite(b.minX)) {
    return canvasData;
  }
  return _objectSpread(_objectSpread({}, canvasData), {}, {
    metricContentSize: {
      width: Math.abs(b.maxX - b.minX),
      height: Math.abs(b.maxY - b.minY)
    }
  });
};