import { generateUUID } from '../../../../../utils/misc';
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 { RemoveChildrenAction } from '../../actions/remove-child-action';
import { SyncUpSelectionAction } from '../../actions/sync-up-selection-action';
import { RTETextBlock } from '../../blocks/text-block';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Convert the selected list block to paragraph strategy.
 */
export class ListTransformToParagraphStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    let isSelectedFirstBlock = false;
    let isSelectedLastBlock = false;
    const selectedBlocks = action.selectedBlocks;
    const currentParagraph = selectedBlocks.map((block) => {
      block.children.map((node) => node.apply(new SyncUpSelectionAction()));
      if (block === target.children[0])
        isSelectedFirstBlock = true;
      if (block === target.children[target.children.length - 1])
        isSelectedLastBlock = true;
      return this.toParagraph(block);
    });
    if (isSelectedFirstBlock) {
      target.parent.apply(new InsertChildrenBeforeAction(target, ...currentParagraph));
    }
    else if (isSelectedLastBlock) {
      target.parent.apply(new InsertChildrenAfterAction(target, ...currentParagraph));
    }
    else {
      const startIndex = target.children.indexOf(selectedBlocks[0]);
      const lastIndex = target.children.indexOf(selectedBlocks[selectedBlocks.length - 1]);
      const firstBulletList = target.parent.createList(target.type);
      firstBulletList.apply(new AppendChildrenAction(target.children.slice(0, startIndex)));
      const lastBulletList = target.parent.createList(target.type);
      lastBulletList.apply(new AppendChildrenAction(target.children.slice(lastIndex + 1)));
      target.parent.apply(new InsertChildrenBeforeAction(target, firstBulletList, ...currentParagraph, lastBulletList));
      target.parent.apply(new RemoveChildrenAction(target));
    }
    selectedBlocks.map((block) => {
      target.apply(new RemoveChildrenAction(block));
    });
    if (target.children.length === 0) {
      target.parent.apply(new RemoveChildrenAction(target));
    }
  }
  /**
   * Converts a RTEListItemBlock to a RTETextBlock representing a paragraph.
   *
   * @param {RTEListItemBlock} block - The block that will be covered
   * @returns {RTETextBlock} Returns a `RTETextBlock`.
   */
  toParagraph(block) {
    const textBlock = new RTETextBlock(generateUUID(), 'paragraph');
    textBlock.apply(new AppendChildrenAction(block['children']));
    textBlock['annotationMap'] = block['annotationMap'];
    return textBlock;
  }
}
