"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.designDataHandler = designDataHandler;
exports.getDesignData = getDesignData;
exports.updateConfiguratorState = updateConfiguratorState;
var _get = _interopRequireDefault(require("lodash/get"));
var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));
var _escape = _interopRequireDefault(require("lodash/escape"));
var _unescape = _interopRequireDefault(require("lodash/unescape"));
var _set = _interopRequireDefault(require("../../../Utils/Immutable/set"));
var _Actions = require("./Actions");
var _Selectors = require("../ImageGallery/Selectors");
var _Selectors2 = require("./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 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); }
function getDesignData(configuratorState) {
  return (0, _get["default"])(configuratorState, 'configuration.designdata');
}
function updateConfiguratorState(state, designAreaIdentifier, designData) {
  var currentDesignData = getDesignData(state) || {};
  return _objectSpread(_objectSpread({}, state), {}, {
    configuration: _objectSpread(_objectSpread({}, state.configuration), {}, {
      designdata: _objectSpread(_objectSpread({}, currentDesignData), {}, _defineProperty({}, designAreaIdentifier, _objectSpread(_objectSpread({}, currentDesignData[designAreaIdentifier]), designData)))
    })
  });
}
var regExpEscape = function regExpEscape(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};
function shouldItemHaveBackgroundColor(item) {
  if (item.type === 'Text') {
    return (0, _Selectors2.hasBackgroundColor)(item.style.colors);
  } else if (item.type === 'Image') {
    if ((0, _get["default"])(item, 'imageData.operations.vectorize')) {
      var objectColors = Object.values((0, _get["default"])(item, 'imageData.operations.vectorizeColorsMap') || {});
      return (0, _Selectors2.hasBackgroundColor)(objectColors);
    }
  }
  return false;
}
function updateItemHasBackgroundColor(state, designAreaIdentifier) {
  var objectsPath = "configuration.designdata.".concat(designAreaIdentifier, ".canvasData.objects");
  var objects = (0, _get["default"])(state, objectsPath, []);
  return (0, _set["default"])(state, objectsPath, objects.map(function (object) {
    return shouldItemHaveBackgroundColor(object) ? _objectSpread(_objectSpread({}, object), {}, {
      hasBackgroundColor: true
    }) : object;
  }));
}
function designDataHandler(state, action) {
  var designAreaIdentifier = action.designAreaIdentifier;
  switch (action.type) {
    case _Actions.actionTypes.SET_CANVAS_DATA:
      {
        var canvasData = action.canvasData;
        var nextState = updateConfiguratorState(state, designAreaIdentifier, {
          canvasData: canvasData
        });
        return updateItemHasBackgroundColor(nextState, designAreaIdentifier);
      }
    case _Actions.actionTypes.SET_CANVAS_DATA_MAP:
      {
        var canvasDataMap = action.canvasDataMap;
        return Object.keys(canvasDataMap).reduce(function (state, designAreaIdentifier) {
          var nextState = updateConfiguratorState(state, designAreaIdentifier, {
            canvasData: canvasDataMap[designAreaIdentifier]
          });
          return updateItemHasBackgroundColor(nextState, designAreaIdentifier);
        }, state);
      }
    case _Actions.actionTypes.SET_DESIGN_PRODUCTION_METHOD:
      {
        var designProductionMethodIdentifier = action.designProductionMethodIdentifier;
        return updateConfiguratorState(state, designAreaIdentifier, {
          designProductionMethodIdentifier: designProductionMethodIdentifier
        });
      }
    case _Actions.actionTypes.SET_COLOR_AMOUNT:
      {
        var colorAmount = action.colorAmount;
        return updateConfiguratorState(state, designAreaIdentifier, {
          colorAmount: colorAmount
        });
      }
    case _Actions.actionTypes.SET_INITIAL_DESIGN_DATA:
      {
        var initialDesignData = action.initialDesignData;
        return _objectSpread(_objectSpread({}, state), {}, {
          configuration: _objectSpread(_objectSpread({}, state.configuration), {}, {
            designdata: initialDesignData
          })
        });
      }
    case _Actions.actionTypes.UPDATE_IMAGE_DATA:
      {
        var _designAreaIdentifier = action.designAreaIdentifier,
          imageData = action.imageData,
          originalImageIdentifier = action.originalImageIdentifier;
        var designdata = (0, _cloneDeep["default"])(getDesignData(state));
        var areas = _designAreaIdentifier ? [_designAreaIdentifier] : Object.keys(designdata);
        areas.forEach(function (area) {
          var objects = (0, _get["default"])(designdata[area], 'canvasData.objects', []);
          objects.forEach(function (object) {
            if (object.imageData && (originalImageIdentifier && object.imageData.identifier === originalImageIdentifier || object.imageData.identifier === imageData.identifier)) {
              object.imageData = (0, _cloneDeep["default"])(imageData);
              object.src = (0, _Selectors.getPreviewUrlFromImageData)(object.imageData.preview);
            }
          });
        });
        return _objectSpread(_objectSpread({}, state), {}, {
          configuration: _objectSpread(_objectSpread({}, state.configuration), {}, {
            designdata: designdata
          })
        });
      }
    case _Actions.actionTypes.SET_DESIGN_AREA_TEXTS_COLOR:
      {
        var objectsPath = "configuration.designdata.".concat(action.identifier, ".canvasData.objects");
        var objects = (0, _get["default"])(state, objectsPath, []);
        return (0, _set["default"])(state, objectsPath, objects.map(function (object) {
          if (object.type !== 'Text') {
            return object;
          }
          var content = object.content.replace(/#[0-9a-f]{3,6}/gi, action.color.value).replace(/rgb\([^)]+\)/gi, action.color.value).replace(/data-color="([^"]+)"/gi, "data-color='".concat(action.color.identifier, "'"));
          return _objectSpread(_objectSpread({}, object), {}, {
            content: content
          });
        }));
      }
    case _Actions.actionTypes.REPLACE_DESIGN_AREA_TEXTS_COLOR:
      {
        var _objectsPath = "configuration.designdata.".concat(action.identifier, ".canvasData.objects");
        var _objects = (0, _get["default"])(state, _objectsPath, []);
        return (0, _set["default"])(state, _objectsPath, _objects.map(function (object) {
          if (object.type !== 'Text') {
            return object;
          }
          var colorToReplace = Object.values(action.oldValue).map(regExpEscape).join('|');
          var content = object.content.replace(/data-color="(.*?)"/gi, function (originalAttr, dataAttr) {
            return (0, _unescape["default"])(dataAttr) === action.oldColorData ? "data-color=\"".concat((0, _escape["default"])(action.colorData), "\"") : originalAttr;
          }).replace(new RegExp("<([^<]*)color: (".concat(colorToReplace, ");([^>]*)>"), 'gi'), "<$1color: ".concat(action.value, ";$3>"));
          return _objectSpread(_objectSpread({}, object), {}, {
            content: content
          });
        }));
      }
    default:
      {
        return state;
      }
  }
}