import RTEDTOClassManager from '../../../../../helpers/rte-manager/dto-class-manager';
import { generateUUID } from '../../../../../utils/misc';
import { ActionHandlerInterceptor, } from '../../../dto/action-handle-strategies/action-handle-interceptor.abstract';
import { InsertChildrenAfterAction } from '../../../dto/actions/insert-children-after-block';
import { InsertChildrenBeforeAction } from '../../../dto/actions/insert-children-before-block';
/**
 * Interceptor to insert a paragraph before or after a table block.
 */
export class PreventTableInsertParagraphInterceptor extends ActionHandlerInterceptor {
  /**
   * Intercept insert paragraph action when table block has a parent.
   *
   * @param {InsertNewParagraphAction} _action - the action to be intercepted
   * @param {RTETableBlock} target - the target table block
   * @returns {boolean} - whether the action should be intercepted
   */
  canIntercept(_action, target) {
    return Boolean(target.parent);
  }
  /**
   * Insert a new paragraph block before or after the current table block based on caret offset.
   *
   * @param {ActionHandlerExecution} _execution - the original execution function
   * @param {InsertNewParagraphAction} action - the action containing insert metadata
   * @param {RTETableBlock} target - the target table block
   */
  intercept(_execution, action, target) {
    const newParagraph = this.createNewParagraph('');
    if (newParagraph) {
      if (action.startOffset === 0) {
        target.parent.apply(new InsertChildrenBeforeAction(target, newParagraph));
      }
      else {
        target.parent.apply(new InsertChildrenAfterAction(target, newParagraph));
      }
      action.newBlock = newParagraph;
    }
  }
  /**
   * Create a new empty paragraph block.
   *
   * @param {string} text - paragraph text
   * @returns {Nullable<RTETextBlock>} - paragraph block when paragraph dto class is available
   */
  createNewParagraph(text) {
    const dtoClass = RTEDTOClassManager.getRTEBlockClass('paragraph');
    if (dtoClass) {
      return dtoClass.from({
        id: generateUUID(),
        type: 'paragraph',
        nodes: [{ id: generateUUID(), type: 'text', text }],
      });
    }
  }
}
