import { generateUUID } from '../../../../../utils/misc';
import { AppendChildrenAction } from '../../actions/append-child-nodes-action';
import { InsertChildrenAfterAction } from '../../actions/insert-children-after-block';
import { RemoveChildrenAction } from '../../actions/remove-child-action';
import { RTETextBlock } from '../../blocks/text-block';
import { RTETextNode } from '../../nodes/text-node';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Insert a line break node into multiple blocks selection at special position strategy.
 */
export class ImageInsertLineBreakWithBlocksStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    action.lineBreakNode = this.lineBreakMultipleBlocks(action.selectedBlocks, target);
  }
  /**
   * Inserts a new paragraph block with a line break after a selected block of text in a rich text editor.
   *
   * @param {RTEBlock[]} selectedBlocks - An array of RTEBlock objects that represent the blocks that have been selected for a specific action in the Rich Text Editor.
   * @param {RTEImageBlock} target - The image block.
   * @returns {Nullable<RTETextNode>} Returns a Nullable RTETextNode.
   */
  lineBreakMultipleBlocks(selectedBlocks, target) {
    const newParagraph = RTETextBlock.from({
      id: generateUUID(),
      type: 'paragraph',
      nodes: [{ id: generateUUID(), type: 'text', text: '\n' }],
    });
    target.parent.apply(new InsertChildrenAfterAction(target, newParagraph));
    const afterNodes = this.concatBlocksNodes(selectedBlocks.slice(1));
    if (afterNodes.length === 0 || (afterNodes[0] && afterNodes[0].text === '')) {
      afterNodes.push(new RTETextNode(generateUUID(), '\n', newParagraph));
    }
    newParagraph.apply(new AppendChildrenAction(afterNodes));
    return newParagraph['children'][0];
  }
  /**
   * Concat the child nodes of multiple RTEBlocks if both are not images.
   *
   * @param {RTEBlock[]} blocks - multiple block of content in a rich text editor, such as a paragraph, heading, image, etc.
   * @returns {RTENode[]} Array of connected block nodes
   */
  concatBlocksNodes(blocks) {
    const nodes = [];
    blocks.map((block) => {
      if (block.type !== 'image') {
        nodes.push(...block.children);
        block.parent.apply(new RemoveChildrenAction(block));
      }
    });
    return nodes;
  }
}
