"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.replacePastedDataId = exports.replaceNodeId = exports.decorateOperation = void 0;
var _deepCopy = _interopRequireDefault(require("deep-copy"));
var _slugid = _interopRequireDefault(require("slugid"));
var OPERATION = _interopRequireWildcard(require("./constants"));
var _objectUtils = _interopRequireDefault(require("../../../utils/object-utils"));
const decorateOperation = operation => {
  let newOperation = (0, _deepCopy.default)(operation);
  const {
    type
  } = newOperation;
  switch (type) {
    case OPERATION.INSERT_NODE:
      {
        let {
          node
        } = newOperation;
        if (!node.id) node.id = _slugid.default.nice(); // generate an id for insert node
        break;
      }
    case OPERATION.SPLIT_NODE:
      {
        // child: split [7, 0] -> [[7, 0],[7, 1]]
        // parent: split [[7, 0], [7, 1]] -> [[7], [8]]
        const {
          properties = {}
        } = newOperation;
        // need generate a new id for new node
        properties.id = _slugid.default.nice();
        break;
      }
    default:
      {
        break;
      }
  }
  return newOperation;
};
exports.decorateOperation = decorateOperation;
const replaceNodeId = node => {
  if (!_objectUtils.default.isObject(node)) return node;
  if (_objectUtils.default.hasProperty(node, 'children')) {
    return {
      ...node,
      id: _slugid.default.nice(),
      children: replacePastedDataId(node.children)
    };
  }
  return {
    ...node,
    id: _slugid.default.nice()
  };
};
exports.replaceNodeId = replaceNodeId;
const replacePastedDataId = pastedData => {
  // If children is malformed, return a list of correct child nodes
  if (_objectUtils.default.isObject(pastedData)) {
    return replaceNodeId(pastedData);
  }
  if (!Array.isArray(pastedData)) return [{
    id: _slugid.default.nice(),
    text: ''
  }];
  return pastedData.map(item => {
    item.id = _slugid.default.nice();
    if (item.children) {
      item.children = replacePastedDataId(item.children);
    }
    return item;
  });
};
exports.replacePastedDataId = replacePastedDataId;