import { lastNonWhitespaceIndex } from "../../../base/common/strings.mjs";
import { EditOperation } from "../core/editOperation.mjs";
import { Range } from "../core/range.mjs";
class TrimTrailingWhitespaceCommand {
  constructor(selection, cursors) {
    this._selection = selection;
    this._cursors = cursors;
    this._selectionId = null;
  }
  getEditOperations(model, builder) {
    const ops = trimTrailingWhitespace(model, this._cursors);
    for (let i = 0, len = ops.length; i < len; i++) {
      const op = ops[i];
      builder.addEditOperation(op.range, op.text);
    }
    this._selectionId = builder.trackSelection(this._selection);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this._selectionId);
  }
}
function trimTrailingWhitespace(model, cursors) {
  cursors.sort((a, b) => {
    if (a.lineNumber === b.lineNumber) {
      return a.column - b.column;
    }
    return a.lineNumber - b.lineNumber;
  });
  for (let i = cursors.length - 2; i >= 0; i--) {
    if (cursors[i].lineNumber === cursors[i + 1].lineNumber) {
      cursors.splice(i, 1);
    }
  }
  const r = [];
  let rLen = 0;
  let cursorIndex = 0;
  const cursorLen = cursors.length;
  for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
    const lineContent = model.getLineContent(lineNumber);
    const maxLineColumn = lineContent.length + 1;
    let minEditColumn = 0;
    if (cursorIndex < cursorLen && cursors[cursorIndex].lineNumber === lineNumber) {
      minEditColumn = cursors[cursorIndex].column;
      cursorIndex++;
      if (minEditColumn === maxLineColumn) {
        continue;
      }
    }
    if (lineContent.length === 0) {
      continue;
    }
    const lastNonWhitespaceIndex$1 = lastNonWhitespaceIndex(lineContent);
    let fromColumn = 0;
    if (lastNonWhitespaceIndex$1 === -1) {
      fromColumn = 1;
    } else if (lastNonWhitespaceIndex$1 !== lineContent.length - 1) {
      fromColumn = lastNonWhitespaceIndex$1 + 2;
    } else {
      continue;
    }
    fromColumn = Math.max(minEditColumn, fromColumn);
    r[rLen++] = EditOperation.delete(new Range(lineNumber, fromColumn, lineNumber, maxLineColumn));
  }
  return r;
}
export {
  TrimTrailingWhitespaceCommand,
  trimTrailingWhitespace
};
