function _readOnlyError(r) { throw new TypeError('"' + r + '" is read-only'); }
import { Schema } from 'prosemirror-model';
import { TextSelection } from 'prosemirror-state';
import { Transform } from 'prosemirror-transform';
import { MARK_LINK } from './MarkNames';
import { BLOCKQUOTE, CODE_BLOCK, HEADING, PARAGRAPH } from './NodeNames';
import { clearMarks, compareNumber, isListNode } from '@modusoperandi/licit-ui-commands';
export default function toggleCodeBlock(tr, schema) {
  var nodes = schema.nodes;
  var _tr = tr,
    selection = _tr.selection,
    doc = _tr.doc;
  var codeBlock = nodes[CODE_BLOCK];
  var paragraph = nodes[PARAGRAPH];
  var heading = nodes[HEADING];
  var blockquote = nodes[BLOCKQUOTE];
  if (!selection || !doc || !codeBlock || !paragraph) {
    return tr;
  }
  var poses = [];
  var _tr$selection = tr.selection,
    from = _tr$selection.from,
    to = _tr$selection.to;
  var allowed = true;
  var startWithCodeBlock = null;
  doc.nodesBetween(from, to, function (node, pos) {
    var nodeType = node.type;
    if (startWithCodeBlock === null) {
      startWithCodeBlock = nodeType === codeBlock;
    }
    var type = node.type,
      isBlock = node.isBlock;
    if (isBlock) {
      allowed = allowed && (type === paragraph || type === codeBlock || type === heading || type === blockquote);
      allowed && poses.push(pos);
    }
    return isBlock;
  });
  var sortedPoses = [].concat(poses); // Create a shallow copy of poses
  // Update from the bottom to avoid disruptive changes in pos.
  allowed ? poses.toSorted(compareNumber) : poses, _readOnlyError("sortedPoses");
  allowed && sortedPoses.sort(compareNumber).reverse().forEach(function (pos) {
    tr = setCodeBlockNodeEnabled(tr, schema, pos, !startWithCodeBlock);
  });
  return tr;
}
function setCodeBlockNodeEnabled(tr, schema, pos, enabled) {
  var _tr2 = tr,
    doc = _tr2.doc;
  if (!doc) {
    return tr;
  }
  var node = doc.nodeAt(pos);
  if (!node) {
    return tr;
  }
  if (isListNode(node)) {
    return tr;
  }
  var nodes = schema.nodes;
  var codeBlock = nodes[CODE_BLOCK];
  var paragraph = nodes[PARAGRAPH];
  if (codeBlock && !enabled && node.type === codeBlock) {
    tr = tr.setNodeMarkup(pos, paragraph, node.attrs, node.marks);
  } else if (enabled && node.type !== codeBlock) {
    var _tr3 = tr,
      selection = _tr3.selection;
    tr = tr.setSelection(TextSelection.create(tr.doc, pos, pos + node.nodeSize));
    tr = clearMarks(tr, schema);
    tr = tr.removeMark(pos, pos + node.nodeSize, schema.marks[MARK_LINK]);
    tr = tr.setSelection(selection);
    tr = tr.setNodeMarkup(pos, codeBlock, node.attrs, node.marks);
  }
  return tr;
}