import { AppendChildrenAction } from '../../actions/append-child-nodes-action';
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 image block with a special position strategy.
 */
export class BlockSplitWithImageNodeStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    action.newBlock = this.splitImageNodes(action.splitPointNode, action.startOffsetOfNode, target);
  }
  /**
   * The image offset should be 0 or 1
   * <vega-rich-text-image-editor><img /></vega-rich-text-image-editor>
   *
   * @param {RTEImageNode} imageNode The split point image node.
   * @param {number} imageOffset The cursor point 0 | 1.
   * @param {RTEImageBlock} target The image block.
   * @returns {Nullable<RTEBlock>} The new block after split
   */
  splitImageNodes(imageNode, imageOffset, target) {
    const nodesSplitIndex = target.children.indexOf(imageNode);
    if (nodesSplitIndex > -1) {
      const beforeNodes = target.children.slice(0, nodesSplitIndex + imageOffset);
      const afterNodes = target.children.slice(nodesSplitIndex + imageOffset);
      target.apply(new ReplaceChildNodesAction(beforeNodes));
      const newBlock = this.cloneWithNodes(afterNodes, target);
      target.parent.apply(new InsertChildrenAfterAction(target, newBlock));
      return newBlock;
    }
  }
  /**
   * Creates a new RTEImageBlock instance with the provided RTEImageNode instances appended to it.
   *
   * @param {RTEImageNode[]} nodes - An array of RTEImageNode objects that will be used to create a new RTEImageBlock instance.
   * @param {RTEImageBlock} target The image block.
   * @returns {RTEImageBlock} A new `RTEImageBlock` object with the provided `nodes` appended to it.
   */
  cloneWithNodes(nodes, target) {
    const block = target.createNewImageBlock();
    block.children = [];
    block.apply(new AppendChildrenAction(nodes));
    return block;
  }
}
