"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
exports.imageGalleryReducer = imageGalleryReducer;
var _findIndex = _interopRequireDefault(require("lodash/findIndex"));
var _find = _interopRequireDefault(require("lodash/find"));
var _get = _interopRequireDefault(require("lodash/get"));
var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));
var _isEqual = _interopRequireDefault(require("lodash/isEqual"));
var _Modifiers = require("./Modifiers");
var _Actions = _interopRequireWildcard(require("./Actions"));
var actionTypes = _Actions;
var _Modifiers2 = require("../DesignData/Modifiers");
var _Selectors = require("./Selectors");
var _configuration = require("../../configuration");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
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 _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
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 _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
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 updateDerivedImageDataProps = function updateDerivedImageDataProps(imageData) {
  var _imageData$operations = imageData.operations,
    operations = _imageData$operations === void 0 ? {} : _imageData$operations;
  imageData.imageColorsWereEdited = !!operations.vectorizeOriginalColorsMap && !(0, _isEqual["default"])(operations.vectorizeColorsMap, operations.vectorizeOriginalColorsMap);
  var prevColorPreviewEnabled = imageData.colorPreviewEnabled;
  imageData.colorPreviewEnabled = imageData.colorPreviewRequired || !!Object.keys(operations.vectorizeOriginalColorsMap || {}).length && (0, _Modifiers2.isOneColorAboveThreshold)(operations.vectorizeColorsMap, operations.vectorizeOriginalColorsMap);
  if (!imageData.colorPreviewEnabled) {
    imageData.displayColorPreview = false;
  } else if (!prevColorPreviewEnabled) {
    imageData.displayColorPreview = (0, _configuration.getConf)('autoPreviewVectorization', true);
  }
  if (imageData.vectorizedLogoMandatory) {
    imageData.colorPreviewEnabled = false;
    imageData.displayColorPreview = true;
  }
  return imageData;
};
var initialState = {
  gallery: [],
  tags: [],
  selectedTag: null,
  selectedTags: [],
  userImages: [],
  selectedImage: null,
  lastErrorCode: null,
  mode: null,
  uploadDelayed: false
};
function imageGalleryReducer() {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
  var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  switch (action.type) {
    case actionTypes.RECEIVE_GALLERY:
      return _objectSpread(_objectSpread({}, state), {}, {
        gallery: action.data
      });
    case actionTypes.RECEIVE_GALLERY_TAGS:
      return _objectSpread(_objectSpread({}, state), {}, {
        tags: action.data
      });
    case actionTypes.SELECT_GALLERY_TAG:
      return _objectSpread(_objectSpread({}, state), {}, {
        selectedTag: action.tag
      });
    case actionTypes.SELECT_GALLERY_TAGS:
      {
        return _objectSpread(_objectSpread({}, state), {}, {
          selectedTags: action.tags
        });
      }
    case actionTypes.RECEIVE_IMAGE_UPLOAD_DATA:
      {
        var statusCode = (0, _get["default"])(action, 'response.status');
        if (statusCode && statusCode !== 200) {
          return _objectSpread(_objectSpread({}, state), {}, {
            lastErrorCode: (0, _get["default"])(action, 'data.code', 'unknown_server_error')
          });
        }
        var imageData = _objectSpread(_objectSpread({}, action.imageData), action.data);
        var userImages = state.userImages;
        var userImage = (0, _find["default"])(userImages, {
          identifier: imageData.identifier
        }) || state.selectedImage;
        if (userImage) {
          imageData.identifier = userImage.identifier;
          if (userImage.originalFileName === imageData.originalFileName) {
            imageData.displayColorPreview = userImage.displayColorPreview;
            if (!imageData.operations) {
              imageData.operations = (0, _cloneDeep["default"])(userImage.operations);
            }
          }
        }
        if (!imageData.identifier || action.createCopy) {
          imageData.identifier = (0, _Modifiers.generateImageId)();
        }
        updateDerivedImageDataProps(imageData);
        if (action.createCopy && action.immediateCommit) {
          userImages = [].concat(state.userImages);
          userImages.push(imageData);
        }
        return _objectSpread(_objectSpread({}, state), {}, {
          userImages: userImages,
          selectedImage: imageData,
          lastErrorCode: null // clear the error code if succeeded
        });
      }

    case actionTypes.COMMIT_CHANGES:
      {
        var count = action.imageUsageInfo.count,
          compatibilityInfoHash = action.compatibilityInfoHash;
        var selectedImage = state.selectedImage,
          mode = state.mode;
        var _userImages = [].concat(state.userImages);
        var identifier = selectedImage.identifier,
          fileName = selectedImage.fileName,
          operations = selectedImage.operations;
        var currentImage = mode === _Actions.ImageGalleryModes.add ? (0, _find["default"])(_userImages, {
          fileName: fileName,
          operations: operations,
          compatibilityInfoHash: compatibilityInfoHash
        }) // try to find an existing one with the same options
        : count === 1 // if it's the only image, find it by identifier
        ? (0, _find["default"])(_userImages, {
          identifier: identifier
        }) : (0, _find["default"])(_userImages, {
          identifier: identifier,
          operations: operations,
          compatibilityInfoHash: compatibilityInfoHash
        }) || null;
        if (currentImage) {
          if (mode === _Actions.ImageGalleryModes.add) {
            return _objectSpread(_objectSpread({}, state), {}, {
              selectedImage: currentImage
            });
          } else {
            var idx = _userImages.indexOf(currentImage);
            _userImages[idx] = _objectSpread(_objectSpread({}, currentImage), selectedImage);
            return _objectSpread(_objectSpread({}, state), {}, {
              userImages: _userImages
            });
          }
        }
        var newImage = _objectSpread(_objectSpread({}, selectedImage), {}, {
          compatibilityInfoHash: compatibilityInfoHash,
          operations: operations || {},
          identifier: (0, _Modifiers.generateImageId)()
        });
        _userImages.push(newImage);
        return _objectSpread(_objectSpread({}, state), {}, {
          userImages: _userImages,
          selectedImage: newImage
        });
      }
    case actionTypes.SET_MODE:
      {
        var _mode = action.mode;
        return _objectSpread(_objectSpread({}, state), {}, {
          mode: _mode
        });
      }
    case actionTypes.SET_SELECTED_IMAGE:
      {
        var _imageData = action.imageData,
          _fileName = action.fileName,
          _identifier = action.identifier;
        var _selectedImage = _imageData && updateDerivedImageDataProps(_imageData) || _identifier && (0, _find["default"])(state.userImages, {
          identifier: _identifier
        }) || _fileName && (0, _find["default"])(state.userImages, {
          fileName: _fileName
        }) || null;
        return _objectSpread(_objectSpread({}, state), {}, {
          selectedImage: _selectedImage
        });
      }
    case actionTypes.ADD_IMAGES_FROM_DESIGN_AREA:
      {
        return action.data ? _objectSpread(_objectSpread({}, state), {}, {
          userImages: [].concat(_toConsumableArray(state.userImages), _toConsumableArray(action.data))
        }) : state;
      }
    case actionTypes.UPDATE_IMAGE:
      {
        var _userImages2 = state.userImages;
        var designAreas = action.imageUsageInfo.designAreas,
          imageDataPatch = action.imageDataPatch;
        var _currentImage = state.selectedImage && state.selectedImage.identifier === action.identifier ? state.selectedImage : (0, _find["default"])(_userImages2, {
          identifier: action.identifier
        });
        var image = _objectSpread(_objectSpread({}, _currentImage), imageDataPatch);

        // create new identifier if it's used by multiple areas
        // avoiding unwanted modification of other occurrences
        if (designAreas > 1 && (0, _Selectors.isHardModified)(_currentImage, image)) {
          image.identifier = (0, _Modifiers.generateImageId)();
        }
        updateDerivedImageDataProps(image);
        var result = _objectSpread({}, state);
        result.selectedImage = image;

        // in 'immediate commit' mode the image is directly updated or added
        // so the extra COMMIT_CHANGES action does not have to be performed
        if (action.immediateCommit) {
          result.userImages = _toConsumableArray(_userImages2);
          var _idx = (0, _findIndex["default"])(_userImages2, {
            identifier: image.identifier
          });
          if (_idx !== -1) {
            result.userImages[_idx] = image;
          } else {
            result.userImages.push(image);
          }
        }
        return result;
      }
    case actionTypes.ADD_GALLERY_IMAGE_TO_USER_IMAGES:
      {
        var imageUrl = action.imageUrl,
          thumbUrl = action.thumbUrl,
          _fileName2 = action.fileName,
          vectorizeColorsMap = action.vectorizeColorsMap,
          _compatibilityInfoHash = action.compatibilityInfoHash,
          svgImageSize = action.svgImageSize;
        var _image = (0, _Modifiers.createSVGImageData)({
          imageUrl: imageUrl,
          thumbUrl: thumbUrl,
          fileName: _fileName2,
          svgImageSize: svgImageSize,
          operations: {
            vectorizeColorsMap: vectorizeColorsMap
          }
        });
        return _objectSpread(_objectSpread({}, state), {}, {
          selectedImage: _objectSpread(_objectSpread({}, _image), {}, {
            compatibilityInfoHash: _compatibilityInfoHash
          })
        });
      }
    case actionTypes.DISMISS_ERROR:
      {
        return _objectSpread(_objectSpread({}, state), {}, {
          lastErrorCode: null
        });
      }
    case actionTypes.UPDATE_UPLOAD_DELAYED:
      {
        return _objectSpread(_objectSpread({}, state), {}, {
          uploadDelayed: action.uploadDelayed
        });
      }
    default:
      return state;
  }
}
var _default = exports["default"] = imageGalleryReducer;