import stateEntityRenderingRegistry from '../../../slimmers/controllers/state-entity-rendering-registry';
import { UpdateTextAction } from '../../actions/update-text-action';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Replaces the rich text node selected text strategy.
 */
export class NodeReplaceSelectedTextStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    this.replaceSelectedText(action.textToBeInsert, action.currentRange, target);
  }
  /**
   * Replaces the selected text within a given range with a new text in a TypeScript class.
   *
   * @param {string} text - The new text that will replace the currently selected text within the specified range.
   * @param {RTERange} currentRange - A range of text within a Rich Text Editor (RTE).
   * @param {RTETextNode} target - The RTE text node instance.
   */
  replaceSelectedText(text, currentRange, target) {
    if (currentRange && currentRange.startContainer && currentRange.endContainer) {
      const { startContainer, endContainer, startOffset, endOffset } = currentRange;
      let newText = target.text;
      if (startContainer === endContainer && startOffset === endOffset && text) {
        newText = target.text.slice(0, startOffset) + text + target.text.slice(startOffset);
      }
      else {
        const startNode = startContainer.parentElement;
        const endNode = endContainer.parentElement;
        const startItemDto = startNode && stateEntityRenderingRegistry.getEntityByDOM(startNode);
        const endItemDto = endNode && stateEntityRenderingRegistry.getEntityByDOM(endNode);
        let startIndex = 0, endIndex = target.text.length;
        if (startItemDto && startItemDto === target) {
          startIndex = startOffset;
          endIndex = startContainer === endContainer ? endOffset : endIndex;
        }
        else if (endItemDto && endItemDto === target) {
          endIndex = endOffset;
        }
        newText = target.text.slice(0, startIndex) + text + target.text.slice(endIndex);
      }
      target.apply(new UpdateTextAction(newText));
    }
  }
}
