import { InsertChildrenAfterAction } from '../../actions/insert-children-after-block';
import { ReplaceChildNodesAction } from '../../actions/replace-child-nodes-action';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Split the current node with a special position strategy.
 */
export class BlockSplitWithTextNodeStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    action.newBlock = this.splitTextNodeBlock(action.splitPointNode, action.startOffsetOfNode, target);
  }
  /**
   * Splits a text node at a specified offset within a block of nodes and returns a new block with the split nodes.
   *
   * @param {RTETextNode} splitNode - The text node that will be split
   * @param {number} startOffsetOfNode - The index at which will split the text content of the `splitNode`.
   * @param {RTETextBlock} textBlock - The text block need to be splited.
   * @returns {Nullable<RTEBlock>} return either an RTEBlock object or null.
   */
  splitTextNodeBlock(splitNode, startOffsetOfNode, textBlock) {
    if (splitNode) {
      const beforeText = splitNode.text.slice(0, startOffsetOfNode);
      const afterText = splitNode.text.slice(startOffsetOfNode);
      const nodesSplitIndex = textBlock.children.indexOf(splitNode);
      if (nodesSplitIndex > -1) {
        const beforeNodes = textBlock.children.slice(0, nodesSplitIndex);
        const afterNodes = textBlock.children.slice(nodesSplitIndex + 1);
        if (beforeText) {
          beforeNodes.push(splitNode.cloneWithText(beforeText));
        }
        if (afterText) {
          afterNodes.unshift(splitNode.cloneWithText(afterText));
        }
        textBlock.apply(new ReplaceChildNodesAction(beforeNodes));
        const newBlock = textBlock.cloneWithNodes(afterNodes);
        textBlock.parent.apply(new InsertChildrenAfterAction(textBlock, newBlock));
        return newBlock;
      }
    }
  }
}
