import { AppendChildrenAction } from '../../actions/append-child-nodes-action';
import { RemoveChildrenAction } from '../../actions/remove-child-action';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Append the second block child nodes to the first block child nodes and remove the second block strategy.
 */
export class BlockMergeNodesStrategy extends ActionHandleStrategy {
  /**
   * Merges the child nodes of two RTEBlocks if they have the same type or both are not images.
   *
   * @param {MergeTwoBlocksNodesAction} action - The merge block nodes action instance.
   * @param {RTETextBlock | RTEImageBlock} target - The first text block or image block.
   */
  handleAction(action, target) {
    const anotherBlock = action.blockNeedToBeMerged;
    if (target.type === anotherBlock.type || (target.type !== 'image' && anotherBlock.type !== 'image')) {
      let shouldMergeNodes = anotherBlock.children;
      if (anotherBlock.type !== 'image') {
        shouldMergeNodes = anotherBlock.children.filter((node) => node.text);
      }
      target.apply(new AppendChildrenAction(shouldMergeNodes));
      anotherBlock.parent.apply(new RemoveChildrenAction(anotherBlock));
    }
  }
}
