import { generateUUID } from '../../../../../utils/misc';
import { InsertChildrenBeforeAction } from '../../actions/insert-children-before-block';
import { RemoveChildrenAction } from '../../actions/remove-child-action';
import { RTECodeBlock } from '../../blocks/code-block';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Transform the selected text blocks to a code block strategy.
 */
export class BlockTransformToCodeBlockStrategy extends ActionHandleStrategy {
  /**
   * Get the all select text and create a new code block.
   *
   * @param {TransformToCodeBlockAction} action - The action instance.
   * @param {VegaRTEContent} target - The block top parent instance.
   */
  handleAction(action, target) {
    const selectedBlocks = action.selectedBlocks;
    const codeBlock = new RTECodeBlock(generateUUID(), this.getCodeContent(selectedBlocks), 'plainText');
    target.apply(new InsertChildrenBeforeAction(selectedBlocks[0], codeBlock));
    action.newCodeBlock = codeBlock;
    this.removeSelectBlocks(selectedBlocks, target);
  }
  /**
   * Get the selected text block text content.
   *
   * @param {RTEBlock[]} selectedBlocks - The selected blocks.
   * @returns {string} - The selected text content.
   */
  getCodeContent(selectedBlocks) {
    const selectedTextBlocks = selectedBlocks.filter((item) => item.type !== 'image' && item.type !== 'list-item');
    return selectedTextBlocks
      .map((block) => {
      return block.children.map((node) => node.text).join('');
    })
      .join('\n');
  }
  /**
   * Remove the selected blocks after append new code block.
   *
   * @param {RTEBlock[]} selectedBlocks - The selected blocks.
   * @param {VegaRTEContent} target - The selected block top parent object.
   */
  removeSelectBlocks(selectedBlocks, target) {
    for (let i = 0; i < selectedBlocks.length; i++) {
      target.apply(new RemoveChildrenAction(selectedBlocks[i]));
    }
  }
}
