import { AppendChildrenAction } from '../../actions/append-child-nodes-action';
import { InsertChildrenAfterAction } from '../../actions/insert-children-after-block';
import { InsertChildrenBeforeAction } from '../../actions/insert-children-before-block';
import { SplitBlockWithNodeAction } from '../../actions/split-block-with-node-action';
import { NodeAnnotationTypeEnum } from '../../annotations/node-annotation.abstract';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Insert new paragraph into current block at special position.
 */
export class BlockInsertNewParagraphStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    const { startContainerNode } = action;
    action.newBlock = this.breakSingleBlock(startContainerNode, action.startOffset, target);
  }
  /**
   * breakSingleTextBlock
   *
   * @param {RTETextNode} splitNode -
   * @param {number} startOffsetOfNode -
   * @param {RTEBlock} target -
   * @returns {Nullable<RTEBlock>} Nullable<RTEBlock>
   */
  breakSingleBlock(splitNode, startOffsetOfNode, target) {
    const newParagraph = this.getNewParagraph(splitNode);
    if (newParagraph) {
      if (this.isCaretPositionAtBlockEnd(target, splitNode, startOffsetOfNode)) {
        target.parent.apply(new InsertChildrenAfterAction(target, newParagraph));
      }
      else if (this.isCaretPositionAtBlockStart(target, splitNode, startOffsetOfNode)) {
        target.parent.apply(new InsertChildrenBeforeAction(target, newParagraph));
      }
      else {
        const splitBlockAction = new SplitBlockWithNodeAction(splitNode, startOffsetOfNode);
        target.apply(splitBlockAction);
        return splitBlockAction.newBlock;
      }
      return newParagraph;
    }
  }
  /**
   * Create new Paragraph
   *
   * @param {RTENode} splitNode - The split node of the block.
   * @returns {Nullable<RTETextBlock>} - The new text block.
   */
  getNewParagraph(splitNode) {
    const newParagraph = this.createNewParagraph('');
    if (newParagraph) {
      let textNode = newParagraph.children[0];
      if (splitNode.isTextNode() && splitNode.isContentEditable()) {
        newParagraph.children = [];
        textNode = splitNode.cloneWithText('');
        // The link annotation don't need inherited
        textNode.annotationMap.delete(NodeAnnotationTypeEnum.LINK);
        newParagraph.apply(new AppendChildrenAction([textNode]));
      }
      return newParagraph;
    }
  }
}
