import { AppendChildrenAction } from '../../../dto/actions/append-child-nodes-action';
import { InsertChildrenAfterAction } from '../../../dto/actions/insert-children-after-block';
import { ActionHandleStrategy } from '../../../dto/action-handle-strategies/action-handle-strategy.abstract';
import { generateUUID } from '../../../../../utils/misc';
import { VegaRTEContent } from '../../../dto/content-state';
import { RTETableBlock } from '../dto/table-block';
import { generateTableBody } from '../utils/utils';
/**
 * Strategy to handle the insertion of a block into the rich text editor.
 */
export class InsertTableBlockStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    const tableBlock = this.createTableBlock(action.rowCount, action.columnCount);
    const emptyParagraph = super.createNewParagraph('');
    const referenceBlock = this.getReferenceBlock(target);
    if (referenceBlock) {
      referenceBlock.parent.apply(new InsertChildrenAfterAction(referenceBlock, tableBlock, emptyParagraph));
    }
    else {
      target.apply(new AppendChildrenAction([tableBlock, emptyParagraph]));
    }
    action.nextFocusNode = tableBlock.getFirstNode();
  }
  /**
   * Create a table block with the specified number of rows and columns.
   *
   * @param {number} row - The number of rows in the table.
   * @param {number} column - The number of columns in the table.
   * @returns {RTETableBlock} The created table block.
   */
  createTableBlock(row, column) {
    const normalizedRowCount = Math.max(row, 1);
    const normalizedColumnCount = Math.max(column, 1);
    return RTETableBlock.from({
      id: generateUUID(),
      type: 'table-block',
      children: [generateTableBody(normalizedRowCount, normalizedColumnCount)],
    });
  }
  /**
   * We need to get the correct block if the current target is a block element to avoid nesting blocks.
   *
   * @param {RTEBlock} currentTarget - The current target block or content.
   * @returns {Nullable<RTEBlock>} The reference block.
   */
  getReferenceBlock(currentTarget) {
    if (!(currentTarget instanceof VegaRTEContent)) {
      return currentTarget;
    }
  }
}
