import { SettingEventHandler, TableSettingType } from './setting-event-handler.abstract';
import { RTETableCaptionBlock } from '../dto/table-caption-block';
import { TableCaptionAction } from '../actions/table-caption-action';
import { generateUUID } from '../../../../../utils/misc';
/**
 * Event handler for row operations in a table.
 */
export class CaptionOperationEventHandler extends SettingEventHandler {
  /**
   * @inheritDoc
   */
  canHandle(action) {
    return action[0] === TableSettingType.CAPTION;
  }
  /**
   * Toggle caption state for the target table block when the caption menu item is clicked.
   *
   * @param {Array<string>} action - Table setting payload, e.g. ['CAPTION', 'rte-table-caption'].
   * @param {RTEExtensionContext} _extensionContext - Current editor extension context (unused here).
   * @param {RTETableBlock} tableBlock - Table block that owns the caption.
   */
  execute(action, _extensionContext, tableBlock) {
    const shouldEnable = action[1] === 'rte-table-caption';
    const toggleAction = new TableCaptionAction(shouldEnable);
    const existingCaption = tableBlock.getCaption();
    if (shouldEnable) {
      const hydratedCaption = existingCaption && existingCaption.isNotEmpty()
        ? existingCaption
        : this.createCaptionBlock(existingCaption === null || existingCaption === void 0 ? void 0 : existingCaption.id);
      if (!existingCaption || hydratedCaption !== existingCaption) {
        tableBlock.setCaption(hydratedCaption);
      }
      toggleAction.nextFocusNode = hydratedCaption.getLastNode();
    }
    else {
      if (existingCaption) {
        tableBlock.setCaption(null);
        toggleAction.nextFocusNode = tableBlock.getFirstNode();
      }
    }
    this.syncCursorPosition(tableBlock, toggleAction.nextFocusNode);
  }
  /**
   * Applies a cursor update action so the editor focuses on the resolved node.
   *
   * @param {RTETableBlock} block - Table block currently being toggled.
   * @param {Nullable<RTENode>} focusNode - Target node that should receive the caret.
   */
  syncCursorPosition(block, focusNode) {
    super.syncCursorPosition(block, focusNode);
  }
  /**
   * Build a fresh caption block with a default paragraph + placeholder text.
   *
   * @param {string} id - table-caption id
   * @returns {RTETableCaptionBlock} Newly created caption DTO ready for rendering.
   */
  createCaptionBlock(id) {
    const captionData = {
      id: id !== null && id !== void 0 ? id : generateUUID(),
      type: 'table-caption',
      children: [
        {
          id: generateUUID(),
          type: 'paragraph',
          nodes: [
            {
              id: generateUUID(),
              type: 'text',
              text: '',
            },
          ],
        },
      ],
    };
    return RTETableCaptionBlock.from(captionData);
  }
}
