import { VegaSlimmer } from 'vega-slimmer/core';
/**
 * The abstract class used to control the code block input paste action.
 */
export class CodeInputPaste extends VegaSlimmer {
  /**
   * Delete the selected text from a string.
   *
   * @param {string} oldValue - The original string value.
   * @param {number} contentStartOffset - The start index for deletion.
   * @param {number} length - The length of text to delete.
   * @returns {string} The content after deletion.
   */
  deleteSelectedText(oldValue, contentStartOffset, length) {
    if (length >= oldValue.length) {
      oldValue = '';
    }
    else {
      oldValue = oldValue.slice(0, contentStartOffset) + oldValue.slice(contentStartOffset + length);
    }
    return oldValue;
  }
  /**
   * Collect the code nodes content from the code nodes array.
   *
   * @param {CodeNodeType[]} codeNodes - The code nodes array.
   * @returns {string} The concatenated content of code nodes.
   */
  getCodeNodesContent(codeNodes) {
    return codeNodes.map((codeNode) => codeNode.text).join('');
  }
  /**
   * Stop event propagation.
   *
   * @param {Event} e - The event object.
   */
  stopEventPropagation(e) {
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
  }
  /**
   * Re-calculate the next offset and content after insert or delete operation.
   *
   * @param {CodeBlockRange} range - The current code block range.
   * @param {string} content - The current code content.
   * @param {string} newlyAddedContent - The new content to be inserted.
   * @returns {NextOffsetAndContentResult} The next offset and updated content.
   */
  reCalculateRangeAndContent(range, content, newlyAddedContent) {
    let nextOffset = range.contentOffset;
    let updatedContent = content;
    if (range) {
      if (range.selectedText.length) {
        updatedContent = this.deleteSelectedText(updatedContent, range.contentOffset, range.selectedText.length);
      }
      updatedContent =
        updatedContent.slice(0, range.contentOffset) +
          newlyAddedContent +
          updatedContent.slice(range.contentOffset);
      nextOffset = range.contentOffset + newlyAddedContent.length;
    }
    return { nextOffset, updatedContent };
  }
}
