import { Schema } from 'prosemirror-model';
import { Transform } from 'prosemirror-transform';
import { BLOCKQUOTE, HEADING, LIST_ITEM, PARAGRAPH } from './NodeNames.js';
import { compareNumber } from '@modusoperandi/licit-ui-commands';
import { isInsideListItem } from '@modusoperandi/licit-ui-commands';
import { isListNode } from '@modusoperandi/licit-ui-commands';
import { unwrapNodesFromList } from '@modusoperandi/licit-ui-commands';
export default function toggleBlockquote(tr, schema) {
  var nodes = schema.nodes;
  var _tr = tr,
    selection = _tr.selection,
    doc = _tr.doc;
  var heading = nodes[HEADING];
  var blockquote = nodes[BLOCKQUOTE];
  var paragraph = nodes[PARAGRAPH];
  var listItem = nodes[LIST_ITEM];
  if (!selection || !doc || !heading || !paragraph || !listItem) {
    return tr;
  }
  var _tr$selection = tr.selection,
    from = _tr$selection.from,
    to = _tr$selection.to;
  var startWithBlockQuote = null;
  var poses = [];
  doc.nodesBetween(from, to, function (node, pos, parentNode) {
    var nodeType = node.type;
    var parentNodeType = parentNode.type;
    if (startWithBlockQuote === null) {
      startWithBlockQuote = nodeType === blockquote;
    }
    if (parentNodeType !== listItem) {
      poses.push(pos);
    }
    return !isListNode(node);
  });
  // Update from the bottom to avoid disruptive changes in pos.
  poses.sort(compareNumber).reverse().forEach(function (pos) {
    tr = setBlockquoteNode(tr, schema, pos);
  });
  return tr;
}
function setBlockquoteNode(tr, schema, pos) {
  var nodes = schema.nodes;
  var heading = nodes[HEADING];
  var paragraph = nodes[PARAGRAPH];
  var blockquote = nodes[BLOCKQUOTE];
  if (pos >= tr.doc.content.size) {
    // Workaround to handle the edge case that pos was shifted caused by `toggleList`.
    return tr;
  }
  var node = tr.doc.nodeAt(pos);
  if (!node || !heading || !paragraph) {
    return tr;
  }
  var nodeType = node.type;
  if (isInsideListItem(tr.doc, pos)) {
    return tr;
  } else if (isListNode(node)) {
    // Toggle list
    if (blockquote) {
      tr = unwrapNodesFromList(tr, schema, pos, function (paragraphNode) {
        var content = paragraphNode.content,
          marks = paragraphNode.marks,
          attrs = paragraphNode.attrs;
        return blockquote.create(attrs, content, marks);
      });
    }
  } else if (nodeType === blockquote) {
    // Toggle heading
    tr = tr.setNodeMarkup(pos, paragraph, node.attrs, node.marks);
  } else if (nodeType === paragraph || nodeType === heading) {
    tr = tr.setNodeMarkup(pos, blockquote, node.attrs, node.marks);
  }
  return tr;
}