import { generateUUID } from '../../../../../utils/misc';
import { RTETableCaptionBlock } from '../dto/table-caption-block';
import { ElementToDTOStrategy } from '../../../slimmers/controllers/helper/element-to-dto-strategy/element-to-dto-strategy.abstract';
import htmlElementToAnnotationGenerator from '../../../slimmers/controllers/helper/element-to-dto-strategy/annotation-handler/html-element-to-annotation-generator';
import { RTE_TABLE_HEAD_DEFAULT_BACKGROUND_COLOR } from '../constants/styles.constants';
import { RTETableColorManager } from '../utils/table-color-manager';
/**
 * Strategy to convert a native HTML table caption container element into an RTETableCaptionBlock DTO.
 *
 * This expects to be applied to the rendered caption container that wraps the actual caption content
 * (for example, the `div.v-rte--extension-table-caption` element that Stencil renders for table captions).
 */
export class CaptionToCaptionBlockStrategy extends ElementToDTOStrategy {
  /**
   * @inheritDoc
   */
  canHandle(elementsArray, currentIndex) {
    const element = elementsArray[currentIndex];
    return element &&
      element.parentElement &&
      element.parentElement.tagName === 'TABLE' &&
      element.tagName === 'CAPTION'
      ? 1
      : 0;
  }
  /**
   * @inheritDoc
   */
  handle(elementsArray, options) {
    const captionAnnotations = this.getTableCaptionAnnotations(elementsArray[0], options);
    return RTETableCaptionBlock.from({
      id: generateUUID(),
      type: 'table-caption',
      annotations: Object.assign(Object.assign({}, captionAnnotations), { caption: true }),
      children: [],
    }, options);
  }
  /**
   * @inheritDoc
   */
  appendChildBlocks(currentBlock, childBlocks) {
    currentBlock.children = childBlocks.map((block) => {
      block.parent = currentBlock;
      return block;
    });
  }
  /**
   * @inheritDoc
   */
  shouldProceedToElementChildren() {
    return true;
  }
  /**
   * Generates annotations for a table caption element.
   *
   * @param {HTMLElement} element The HTML element representing the table head.
   * @param {VegaRTETransformOptions} options Optional transformation options.
   * @returns {VegaRTETableCaptionBlock['annotations']} The annotations for the table head element.
   */
  getTableCaptionAnnotations(element, options) {
    const result = htmlElementToAnnotationGenerator.generate(RTETableCaptionBlock, element, options);
    if (result && result.customStyle && result.customStyle.backgroundColor) {
      // If the background color matches the default, remove it from the annotation to avoid unnecessary styling
      const colorKey = RTETableColorManager.getColorKey(result.customStyle.backgroundColor, true);
      if (colorKey === RTE_TABLE_HEAD_DEFAULT_BACKGROUND_COLOR.key) {
        // Delete from customStyle as well if it exists to prevent redundant default color styling
        delete result.customStyle.backgroundColor;
      }
    }
    return result;
  }
}
