import { ActionHandlerInterceptor, } from '../../../dto/action-handle-strategies/action-handle-interceptor.abstract';
import { RTETextBlock } from '../../../dto/blocks/text-block';
import { AppendChildrenAction } from '../../../dto/actions/append-child-nodes-action';
import { RTETextNode } from '../../../dto/nodes/text-node';
import { generateUUID } from '../../../../../utils/misc';
/**
 * Interceptor to prevent removal of all children from a cell, ensuring at least one child remains.
 */
export class PreventCellChildrenRemoveInterceptor extends ActionHandlerInterceptor {
  /**
   * Prevent removal if the target cell would be left empty after the action.
   *
   * @param {RemoveChildrenAction} action - the action to be intercepted
   * @param {RTETableCellBlock | RTETableHeadCellBlock} target - the target cell block
   * @returns {boolean} - true if the removal should be intercepted, false otherwise
   */
  canIntercept(action, target) {
    return action.entityToBeRemoved && target.children.length === 1;
  }
  /**
   * Add a new empty text node to the cell to prevent it from removal.
   *
   * @param {ActionHandlerExecution} _execution - the original execution function
   * @param {RemoveChildrenAction} action - the action to be intercepted
   * @param {RTETableCellBlock | RTETableHeadCellBlock} target - the target cell block
   */
  intercept(_execution, action, target) {
    if (!(action.entityToBeRemoved instanceof RTETextBlock)) {
      const newParagraph = RTETextBlock.from({
        id: generateUUID(),
        type: 'paragraph',
        nodes: [{ id: generateUUID(), type: 'text', text: '' }],
      });
      target.children = [];
      target.apply(new AppendChildrenAction([newParagraph]));
      return;
    }
    action.entityToBeRemoved.apply(new AppendChildrenAction([
      new RTETextNode(generateUUID(), '', action.entityToBeRemoved),
    ]));
  }
}
