import { createToggleBlockMarkOnRangeNext } from '../commands';
var getDefaultBlockNodeTypes = function getDefaultBlockNodeTypes(tr) {
  var paragraph = tr.doc.type.schema.nodes.paragraph;
  return paragraph ? [paragraph] : [];
};
export var getBlockMarkAttrs = function getBlockMarkAttrs(node, markType) {
  if (!node || !markType) {
    return false;
  }
  var blockMark = node.marks.find(function (mark) {
    return mark.type === markType;
  });
  return blockMark ? blockMark.attrs : false;
};
export var getFirstParagraphBlockMarkAttrs = function getFirstParagraphBlockMarkAttrs(node, markType) {
  if (!node || !markType) {
    return false;
  }
  var paragraph = node.type.schema.nodes.paragraph;
  if (!paragraph) {
    return false;
  }
  var _findFirstParagraphBlockMarkAttrs = function findFirstParagraphBlockMarkAttrs(currentNode) {
    if (currentNode.type === paragraph) {
      return getBlockMarkAttrs(currentNode, markType);
    }
    for (var index = 0; index < currentNode.childCount; index++) {
      var childResult = _findFirstParagraphBlockMarkAttrs(currentNode.child(index));
      if (childResult !== false) {
        return childResult;
      }
    }
    return false;
  };
  return _findFirstParagraphBlockMarkAttrs(node);
};
export var reconcileBlockMarkInRange = function reconcileBlockMarkInRange(tr, from, to, markType, markAttrs) {
  var blockNodeTypes = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : getDefaultBlockNodeTypes(tr);
  if (!markType || blockNodeTypes.length === 0) {
    return false;
  }
  return createToggleBlockMarkOnRangeNext(markType, function () {
    return markAttrs;
  }, blockNodeTypes)(from, to, tr);
};
export var reconcileBlockMarkForContainerAtPos = function reconcileBlockMarkForContainerAtPos(tr, containerPos, markType, markAttrs) {
  var blockNodeTypes = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : getDefaultBlockNodeTypes(tr);
  var containerNode = tr.doc.nodeAt(containerPos);
  if (!containerNode) {
    return false;
  }
  return reconcileBlockMarkInRange(tr, containerPos, containerPos + containerNode.nodeSize, markType, markAttrs, blockNodeTypes);
};
export var reconcileBlockMarkForParagraphAtPos = function reconcileBlockMarkForParagraphAtPos(tr, pos, markType, markAttrs) {
  var paragraph = tr.doc.type.schema.nodes.paragraph;
  if (!paragraph) {
    return false;
  }
  var resolvedPos = tr.doc.resolve(Math.max(0, Math.min(pos, tr.doc.content.size)));
  for (var depth = resolvedPos.depth; depth > 0; depth--) {
    var node = resolvedPos.node(depth);
    if (node.type === paragraph) {
      return reconcileBlockMarkInRange(tr, resolvedPos.before(depth), resolvedPos.before(depth) + node.nodeSize, markType, markAttrs, [paragraph]);
    }
  }
  return false;
};