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';
const listDepth = 3;
export const selectionCoversAllListItems = ($from, $to) => {
  // Block level lists
  const listParents = ['bulletList', 'orderedList'];
  if ($from.depth >= listDepth && $to.depth >= listDepth && $from.depth === $to.depth) {
    var _greatGrandparentFrom, _greatGrandparentFrom2;
    // Get grandparents (from)
    const grandparentFrom = $from.node($from.depth - 1);
    const greatGrandparentFrom = $from.node($from.depth - 2);
    // Get grandparents (to)
    const grandparentTo = $to.node($from.depth - 1);
    const 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 const getSliceFromSelection = selection => {
  const {
    from,
    to
  } = selection;
  if (from === to) {
    return Fragment.empty;
  }
  let frag = Fragment.empty;
  const sortedRanges = [...selection.ranges.slice()].sort((a, b) => a.$from.pos - b.$from.pos);
  for (const range of sortedRanges) {
    const {
      $from,
      $to
    } = range;
    const to = $to.pos;
    const 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);
    let finalDepth = depth;
    // For block-level lists (non-nested) specifically use the selection
    if (selectionCoversAllListItems($from, $to)) {
      finalDepth = $from.depth - listDepth;
    }
    const start = $from.start(finalDepth);
    const node = $from.node(finalDepth);
    const content = node.content.cut($from.pos - start, $to.pos - start);
    frag = frag.append(content);
  }
  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 const getFragmentsFromSelection = selection => {
  if (!selection || selection.empty) {
    return null;
  }
  const slice = getSliceFromSelection(selection);
  const content = slice.content;
  const fragment = [];
  content.forEach(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 const getLocalIdsFromSelection = selection => {
  if (!selection) {
    return null;
  }
  if (selection instanceof NodeSelection) {
    if (fg('platform_editor_ai_selection_local_ids')) {
      var _selection$node$attrs;
      const ids = [];
      const 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(node => {
        var _node$attrs;
        if (node.isInline) {
          return false;
        }
        const 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')) {
      const ids = [];
      const ancestorIds = new Set();
      // Collect localIds from each selected cell and its descendants
      selection.forEachCell((cellNode, cellPos) => {
        var _cellNode$attrs;
        const cellLocalId = (_cellNode$attrs = cellNode.attrs) === null || _cellNode$attrs === void 0 ? void 0 : _cellNode$attrs.localId;
        if (cellLocalId) {
          ids.push(cellLocalId);
        }
        cellNode.descendants(node => {
          var _node$attrs2;
          if (node.isInline) {
            return false;
          }
          const localId = (_node$attrs2 = node.attrs) === null || _node$attrs2 === void 0 ? void 0 : _node$attrs2.localId;
          if (localId) {
            ids.push(localId);
          }
        });
        // Collect ancestor localIds (row, table) separately
        const $cell = selection.$anchorCell.doc.resolve(cellPos + 1);
        for (let depth = $cell.depth - 1; depth >= 1; depth--) {
          var _ancestor$attrs;
          const ancestor = $cell.node(depth);
          const localId = (_ancestor$attrs = ancestor.attrs) === null || _ancestor$attrs === void 0 ? void 0 : _ancestor$attrs.localId;
          if (localId) {
            ancestorIds.add(localId);
          }
        }
      });
      const uniqueIds = new Set(ids);
      const uniqueAncestors = [...ancestorIds].filter(id => !uniqueIds.has(id));
      return [...uniqueIds, ...uniqueAncestors];
    }
    // Fall through to default slice-based behavior when gate is off
  } else if (selection.empty) {
    return [selection.$from.parent.attrs.localId];
  }
  const slice = getSliceFromSelection(selection);
  const content = slice.content;
  const ids = [];
  content.forEach(node => {
    var _node$attrs3;
    const localId = (_node$attrs3 = node.attrs) === null || _node$attrs3 === void 0 ? void 0 : _node$attrs3.localId;
    if (localId) {
      ids.push(localId);
    }
  });
  return ids;
};