import { VegaRTEExtensionRenderer } from '../../base-extension-renderer';
import styles from '../table-block-styles.css';
import { DeleteTableBlockAction } from '../actions/delete-table-block-action';
import { TableSettingPopoverRenderer } from './table-setting-popover-renderer';
import { RTETableExtensionAnnotationTypeEnum } from '../annotations/table-annotation';
import { TableDynamicPopoverRenderer } from './table-dynamic-popover-renderer';
import changeManager from '../../../../../helpers/change-manager/change-manager';
import DomNodeSubjectFactory from '../../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-factory';
import { VegaInternalRTEExtensionTableCellsSelectionAnchor } from '../../../../../helpers/event-manager/event-id/vega-internal-event-id';
import { RTETableColorManager } from '../utils/table-color-manager';
/**
 * Renderer for the RTETableBlock.
 */
export class RTETableBlockRenderer extends VegaRTEExtensionRenderer {
  /**
   * @inheritDoc
   */
  doRender(h, renderData, rteContext) {
    const tableSettingPopoverRenderer = new TableSettingPopoverRenderer(rteContext);
    const tableDynamicPopoverRenderer = new TableDynamicPopoverRenderer(RTETableColorManager.getTableColors(), rteContext);
    let tableRef;
    const table = this.renderTable(h, renderData, (ref) => (tableRef = ref));
    const tableSettingPopover = tableSettingPopoverRenderer.render(h, renderData, () => tableRef, tableDynamicPopoverRenderer);
    const tableDynamicPopover = tableDynamicPopoverRenderer.render(h, () => tableRef, renderData);
    const tableAnnotation = renderData.getAnnotationByType(RTETableExtensionAnnotationTypeEnum.TABLE);
    const children = rteContext.editable
      ? [
        h('vega-rich-text-table-selection-widget', {
          // eslint-disable-next-line jsdoc/require-jsdoc
          onVegaRemove: (e) => {
            e.stopPropagation();
            this.handleTableRemove(renderData, tableRef);
          },
          // eslint-disable-next-line jsdoc/require-jsdoc
          onClick: (event) => tableSettingPopoverRenderer.handleTableClick(event, tableRef),
          // eslint-disable-next-line jsdoc/require-jsdoc
          onMouseLeave: () => {
            tableSettingPopoverRenderer.syncSelectedCells();
          },
        }, [
          // Add an extra div as slot container, to make sure the cursor can move to before/end of the table.
          h('div', {
            contentEditable: true,
            ref: this.useRef(renderData),
          }, [table, tableSettingPopover, tableDynamicPopover]),
        ]),
      ]
      : [table];
    const containerStyle = {};
    if (tableAnnotation) {
      const tableStyle = tableAnnotation.renderStyle();
      containerStyle.width = tableStyle.width;
      containerStyle.margin = tableStyle.margin;
    }
    const result = h('div', {
      class: 'v-rte--extension-table-container',
      style: Object.assign({}, containerStyle),
    }, children);
    /**
     * The getter for the children container.
     *
     * @returns {VegaRTERenderResult} - The children container render result.
     */
    result.childrenContainerGetter = () => table;
    return result;
  }
  /**
   * @inheritDoc
   */
  injectRTEScopeStyles() {
    return styles;
  }
  /**
   * Renders the table element.
   *
   * @param {VegaRTECreateElementFunction} h - The create element function.
   * @param {RTETableBlock} renderData - The table block to render.
   * @param {(ref: HTMLElement) => HTMLElement} setTableRef - Set table ref to tableRef
   * @returns {VegaRTERenderResult} - The rendered table element.
   */
  renderTable(h, renderData, setTableRef) {
    var _a;
    return h('table', Object.assign(Object.assign({ key: renderData.id }, (_a = renderData.getCustomAttributesAnnotation()) === null || _a === void 0 ? void 0 : _a.render()), { style: renderData.getStyles(), class: renderData.getClasses(), 
      // eslint-disable-next-line jsdoc/require-jsdoc
      ref: (ref) => {
        this.useRef(renderData)(ref);
        setTableRef(ref);
      } }));
  }
  /**
   * Handles the removal of the table block.
   *
   * @param {RTETableBlock} renderData - The table block to remove.
   * @param {HTMLElement} tableRef - The element that can triggered the table popover open.
   */
  handleTableRemove(renderData, tableRef) {
    renderData.parent.apply(new DeleteTableBlockAction(renderData));
    this.destroySelectionAnchor(tableRef);
  }
  /**
   * Notifies and clears the multi-cell selection anchor associated with the given table reference.
   *
   * @param {HTMLElement} tableRef - The table trigger element used to locate the rich text content container.
   */
  destroySelectionAnchor(tableRef) {
    const container = tableRef.closest('.rich-text-content');
    if (container) {
      const selectionAnchorRef = container.querySelector('.rte-table-selection-popover-anchor');
      if (selectionAnchorRef) {
        changeManager.notify(DomNodeSubjectFactory.getSubject(selectionAnchorRef, VegaInternalRTEExtensionTableCellsSelectionAnchor), {
          host: selectionAnchorRef,
        });
      }
    }
  }
}
