import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
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 _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; }
import { nodeToJSON } from '@atlaskit/editor-json-transformer';
import { Fragment } from '@atlaskit/editor-prosemirror/model';
import { TextSelection, NodeSelection } from '@atlaskit/editor-prosemirror/state';
import { CellSelection } from '@atlaskit/editor-tables/cell-selection';
import { fg } from '@atlaskit/platform-feature-flags';
var listDepth = 3;
export var selectionCoversAllListItems = function selectionCoversAllListItems($from, $to) {
  // Block level lists
  var listParents = ['bulletList', 'orderedList'];
  if ($from.depth >= listDepth && $to.depth >= listDepth && $from.depth === $to.depth) {
    var _greatGrandparentFrom, _greatGrandparentFrom2;
    // Get grandparents (from)
    var grandparentFrom = $from.node($from.depth - 1);
    var greatGrandparentFrom = $from.node($from.depth - 2);
    // Get grandparents (to)
    var grandparentTo = $to.node($from.depth - 1);
    var greatGrandparentTo = $to.node($from.depth - 2);
    if (greatGrandparentTo.eq(greatGrandparentFrom) && listParents.includes(greatGrandparentFrom.type.name) && // Selection covers entire list
    (_greatGrandparentFrom = greatGrandparentFrom.firstChild) !== null && _greatGrandparentFrom !== void 0 && _greatGrandparentFrom.eq(grandparentFrom) && (_greatGrandparentFrom2 = greatGrandparentFrom.lastChild) !== null && _greatGrandparentFrom2 !== void 0 && _greatGrandparentFrom2.eq(grandparentTo)) {
      return true;
    }
  }
  return false;
};

/**
 * Get the slice of the document corresponding to the selection.
 * This is similar to the prosemirror `selection.content()` - but
 * does not include the parents (unless the result is inline)
 *
 * @param selection The selection to get the slice for.
 * @returns The slice of the document corresponding to the selection.
 */
export var getSliceFromSelection = function getSliceFromSelection(selection) {
  var from = selection.from,
    to = selection.to;
  if (from === to) {
    return Fragment.empty;
  }
  var frag = Fragment.empty;
  var sortedRanges = _toConsumableArray(selection.ranges.slice()).sort(function (a, b) {
    return a.$from.pos - b.$from.pos;
  });
  var _iterator = _createForOfIteratorHelper(sortedRanges),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var range = _step.value;
      var $from = range.$from,
        $to = range.$to;
      var _to = $to.pos;
      var depth =
      // If we're in a text selection, and share the parent node across the anchor->head
      // make the depth the parent node
      selection instanceof TextSelection && $from.parent.eq($to.parent) ? Math.max(0, $from.sharedDepth(_to) - 1) : $from.sharedDepth(_to);
      var finalDepth = depth;
      // For block-level lists (non-nested) specifically use the selection
      if (selectionCoversAllListItems($from, $to)) {
        finalDepth = $from.depth - listDepth;
      }
      var start = $from.start(finalDepth);
      var node = $from.node(finalDepth);
      var content = node.content.cut($from.pos - start, $to.pos - start);
      frag = frag.append(content);
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return frag;
};

/**
 * Get the fragments from the selection.
 * @param selection The selection to get the fragments from.
 * @param schema The schema to use to convert the nodes to JSON.
 * @returns The fragments as an array of JSON nodes.
 */
export var getFragmentsFromSelection = function getFragmentsFromSelection(selection) {
  if (!selection || selection.empty) {
    return null;
  }
  var slice = getSliceFromSelection(selection);
  var content = slice.content;
  var fragment = [];
  content.forEach(function (node) {
    fragment.push(nodeToJSON(node));
  });
  return fragment;
};

/**
 * Get the local IDs from the selection.
 * @param selection The selection to get the local IDs from.
 * @returns The local IDs as an array of strings.
 */
export var getLocalIdsFromSelection = function getLocalIdsFromSelection(selection) {
  if (!selection) {
    return null;
  }
  if (selection instanceof NodeSelection) {
    if (fg('platform_editor_ai_selection_local_ids')) {
      var _selection$node$attrs;
      var _ids = [];
      var rootLocalId = (_selection$node$attrs = selection.node.attrs) === null || _selection$node$attrs === void 0 ? void 0 : _selection$node$attrs.localId;
      if (rootLocalId) {
        _ids.push(rootLocalId);
      }
      selection.node.descendants(function (node) {
        var _node$attrs;
        if (node.isInline) {
          return false;
        }
        var localId = (_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : _node$attrs.localId;
        if (localId) {
          _ids.push(localId);
        }
      });
      return _ids;
    }
    return [selection.node.attrs.localId];
  } else if (selection instanceof CellSelection) {
    if (fg('platform_editor_ai_selection_local_ids')) {
      var _ids2 = [];
      var ancestorIds = new Set();
      // Collect localIds from each selected cell and its descendants
      selection.forEachCell(function (cellNode, cellPos) {
        var _cellNode$attrs;
        var cellLocalId = (_cellNode$attrs = cellNode.attrs) === null || _cellNode$attrs === void 0 ? void 0 : _cellNode$attrs.localId;
        if (cellLocalId) {
          _ids2.push(cellLocalId);
        }
        cellNode.descendants(function (node) {
          var _node$attrs2;
          if (node.isInline) {
            return false;
          }
          var localId = (_node$attrs2 = node.attrs) === null || _node$attrs2 === void 0 ? void 0 : _node$attrs2.localId;
          if (localId) {
            _ids2.push(localId);
          }
        });
        // Collect ancestor localIds (row, table) separately
        var $cell = selection.$anchorCell.doc.resolve(cellPos + 1);
        for (var depth = $cell.depth - 1; depth >= 1; depth--) {
          var _ancestor$attrs;
          var ancestor = $cell.node(depth);
          var localId = (_ancestor$attrs = ancestor.attrs) === null || _ancestor$attrs === void 0 ? void 0 : _ancestor$attrs.localId;
          if (localId) {
            ancestorIds.add(localId);
          }
        }
      });
      var uniqueIds = new Set(_ids2);
      var uniqueAncestors = _toConsumableArray(ancestorIds).filter(function (id) {
        return !uniqueIds.has(id);
      });
      return [].concat(_toConsumableArray(uniqueIds), _toConsumableArray(uniqueAncestors));
    }
    // Fall through to default slice-based behavior when gate is off
  } else if (selection.empty) {
    return [selection.$from.parent.attrs.localId];
  }
  var slice = getSliceFromSelection(selection);
  var content = slice.content;
  var ids = [];
  content.forEach(function (node) {
    var _node$attrs3;
    var localId = (_node$attrs3 = node.attrs) === null || _node$attrs3 === void 0 ? void 0 : _node$attrs3.localId;
    if (localId) {
      ids.push(localId);
    }
  });
  return ids;
};