import { ActionHandleStrategyRegistry } from '../../../dto/action-handle-strategies/action-handle-strategy-registry';
import { UpdateCursorPositionAction } from '../../../dto/actions/update-cursor-position-action';
import { VegaRTEToolbarButtonRenderer } from '../../base-toolbar-button-renderer';
import { INSERT_FUNCTION_BLOCK, InsertFunctionBlockAction, } from '../actions/insert-function-block-action';
/**
 * Function toolbar button renderer class.
 */
export class FunctionToolbarButtonRenderer extends VegaRTEToolbarButtonRenderer {
  /**
   * @inheritDoc
   */
  render(h, editorContext) {
    return this.renderDropdown(h, editorContext, {}, [
      this.renderButton(h, editorContext, {
        label: 'Functions',
        showArrowIcon: true,
      }),
      this.renderDropdownListTemplate(h, FunctionToolbarButtonRenderer.FUNCTION_LIST),
    ]);
  }
  /**
   * Overrides the isDisabled method to determine if the button should be disabled.
   *
   * @param {VegaRTEToolbarRenderContext} editorContext The render context for the editor.
   * @returns {boolean} - true if the button should be disabled, false otherwise.
   */
  isDisabled(editorContext) {
    const context = this.getExtensionContext(editorContext.host);
    if (context) {
      const { host, getSelectedNodes } = context;
      const focusNode = getSelectedNodes()[0];
      let enableInsert = true;
      if (focusNode) {
        enableInsert = ActionHandleStrategyRegistry.canHandle(INSERT_FUNCTION_BLOCK, focusNode.parent);
      }
      return host.disabled || !enableInsert;
    }
    return false;
  }
  /* istanbul ignore next */
  // eslint-disable-next-line jsdoc/require-jsdoc
  handleButtonClick() {
    throw new Error('Method not implemented.');
  }
  /**
   * Handles dropdown click event
   *
   * @param {RTEExtensionFunctionType} itemKey - key of the clicked item
   * @param {VegaRTEToolbarRenderContext} editorContext The render context for the editor.
   */
  handleDropdownClick(itemKey, editorContext) {
    if (editorContext) {
      const context = this.getExtensionContext(editorContext.host);
      if (context) {
        const { host, getSelectedNodes } = context;
        const focusNode = getSelectedNodes()[0];
        const action = new InsertFunctionBlockAction(itemKey);
        if (!focusNode) {
          host.value.apply(action);
        }
        else if (focusNode.parent) {
          focusNode.parent.apply(action);
        }
        if (action.nextFocusNode) {
          host.value.apply(new UpdateCursorPositionAction(action.nextFocusNode, 1));
        }
      }
    }
  }
}
FunctionToolbarButtonRenderer.FUNCTION_LIST = [
  { key: 'IF', label: 'Conditional' },
  { key: 'FOREACH', label: 'Foreach' },
];
