import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Insert children at the front of the block strategy.
 */
export class InsertChildrenBeforeStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    this.replaceElementWithElements(target, action.referChildren, [
      ...action.childrenToBeInserted,
      action.referChildren,
    ]);
  }
  /**
   * Replaces a specific block or node with an array of blocks or nodes within RTEContentBlock array.
   *
   * @param {RTEBlock | VegaRTEContent} target - The block or the VegaRTEContent instance.
   * @param {RTEBlock | RTENode} referElement - Used as a reference element to identify the element that needs to be replaced in the array.
   * @param {RTEBlock[] | RTENode[]} elements - An array of block or node objects that you want to replace the `referElement` with in the array.
   */
  replaceElementWithElements(target, referElement, elements) {
    if (target.children) {
      elements.forEach((block) => {
        block.parent = target;
      });
      const arrayFixed = target.children;
      target.children = arrayFixed.flatMap((block) => {
        if (block === referElement) {
          return elements;
        }
        else {
          return block;
        }
      });
    }
  }
}
