import { InsertChildrenAfterAction } from '../../actions/insert-children-after-block';
import { InsertChildrenBeforeAction } from '../../actions/insert-children-before-block';
import { RemoveChildrenAction } from '../../actions/remove-child-action';
import { UpdateCursorPositionAction } from '../../actions/update-cursor-position-action';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Insert a new node in nearest position of parent block strategy.
 */
export class InsertNodeToNearestRootStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    const { rteRange, nodeToBeInserted } = action;
    const { startNode, startOffset } = rteRange;
    if (startNode) {
      const parent = target;
      if (startNode.isContentEditable() && startNode.isTextNode()) {
        if (startNode.text === '\n' || !startNode.text || startOffset === 0) {
          parent.apply(new InsertChildrenBeforeAction(startNode, nodeToBeInserted));
        }
        else {
          const startText = startNode.text.substring(0, startOffset);
          const endText = startNode.text.substring(startOffset);
          const startTextNode = startNode.cloneWithText(startText);
          const endTextNode = startNode.cloneWithText(endText);
          const insertNodes = [startTextNode, nodeToBeInserted];
          if (endText) {
            insertNodes.push(endTextNode);
          }
          parent.apply(new InsertChildrenBeforeAction(startNode, ...insertNodes));
          parent.apply(new RemoveChildrenAction(startNode));
        }
      }
      else {
        if (startOffset !== 0) {
          parent.apply(new InsertChildrenAfterAction(startNode, nodeToBeInserted));
        }
        else {
          parent.apply(new InsertChildrenBeforeAction(startNode, nodeToBeInserted));
        }
      }
      this.updateCursorPosition(nodeToBeInserted);
    }
  }
  /**
   * Update the cursor position to end of the inserted node.
   *
   * @param {RTENode} node - node to find root content
   */
  updateCursorPosition(node) {
    const root = this.getRootContent(node.parent);
    if (root) {
      root.apply(new UpdateCursorPositionAction(node));
    }
  }
}
