var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { VegaSlimmer, MapToComponentField, MapToComponentMethod } from 'vega-slimmer/core';
import { RTETextBlock } from '../../dto/blocks/text-block';
import { RTETextNode } from '../../dto/nodes/text-node';
import stateEntityRenderingRegistry from './state-entity-rendering-registry';
import { ZERO_WIDTH_SPACE } from '../../constants/constant';
import { UpdateTextAction } from '../../dto/actions/update-text-action';
import changeManager from '../../../../helpers/change-manager/change-manager';
import domNodeSubjectFactory from '../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-factory';
import { VegaInternalRichTextEditDeleteSelectedNodes } from '../../../../helpers/event-manager/event-id/vega-internal-event-id';
import { InsertChildrenBeforeAction } from '../../dto/actions/insert-children-before-block';
/** Handles inserting composition text into a VegaRTEContent based on the current selection and input event. User input character will trigger this callback */
export class InsertCompositionTextController extends VegaSlimmer {
  constructor() {
    super(...arguments);
    this.insertCompositionTextEndFlag = true;
    this.observerOptions = {
      characterData: true,
      characterDataOldValue: true,
      subtree: true,
      childList: true,
    };
    /**
     * The current method is called when the insert text is update by the Pinyin input or the word correction plugin.
     *
     * @param {MutationRecord[]} records - The mutation record object array.
     */
    this.updateTextFromDom = (records) => {
      let updateFlag = false;
      if (this.insertCompositionTextEndFlag !== false) {
        records.forEach((record) => {
          const { target, oldValue } = record;
          if (target.nodeType === Node.TEXT_NODE && target.parentElement) {
            const richTextNode = stateEntityRenderingRegistry.getEntityByDOM(target.parentElement);
            const newValue = target.textContent;
            if (richTextNode instanceof RTETextNode &&
              richTextNode.isContentEditable() &&
              richTextNode.parent instanceof RTETextBlock) {
              updateFlag = this.updateCurrentNodeText(richTextNode, newValue, oldValue);
            }
            else if (newValue) {
              // The text element should removed if insert text to the image block.
              target.parentElement.removeChild(target);
              updateFlag = true;
            }
          }
        });
      }
      if (updateFlag) {
        void this.valueController.flushChanges(this.value);
      }
    };
    /**
     * Processes mutation records related to character data and updates the text content of a rich text node accordingly.
     *
     * @param {MutationRecord[]} records - Each `MutationRecord` object represents a single mutation that occurred in the DOM.
     */
    this.handleObserver = (records) => {
      if (records.every((record) => record.type === 'characterData')) {
        this.updateTextFromDom(records);
      }
    };
    /**
     * An event handler function that is triggered when the composition of text input starts. In this case,
     *  it sets the `insertCompositionTextEndFlag` property of the `UserInputController` class to `false`.
     */
    this.handleCompositionStart = () => {
      this.insertCompositionTextEndFlag = false;
      changeManager.notify(domNodeSubjectFactory.getSubject(this.host, VegaInternalRichTextEditDeleteSelectedNodes), { host: this.host, detail: true });
    };
    /**
     * An event handler function that is triggered when the composition of text input ends. In this case,
     *  it sets the `insertCompositionTextEndFlag` property of the `UserInputController` class to `true`.
     *
     * @param {CompositionEvent} event The composition event instance
     */
    this.handleCompositionEnd = (event) => {
      this.insertCompositionTextEndFlag = true;
      const insertData = event.data;
      if (insertData) {
        this.dispatchInsertTextEvent(insertData);
      }
    };
  }
  /**
   * The function `initMutationObserver` initializes a MutationObserver on an editable HTML element if it exists.
   */
  initMutationObserver() {
    if (this.mutationObserver) {
      const editableElement = this.getEditableElementRef();
      if (editableElement) {
        this.mutationObserver.disconnect();
        this.mutationObserver.observe(editableElement, this.observerOptions);
      }
    }
  }
  /**
   * Disconnects the mutation observer if it exists.
   */
  removeObserver() {
    if (this.mutationObserver) {
      this.mutationObserver.disconnect();
    }
  }
  /**
   * The method is to get the composition text insert end or not.
   *
   * @returns {boolean} The false is main that insert composition text process is end.
   */
  isComposing() {
    return !this.insertCompositionTextEndFlag;
  }
  /**
   * Adds event listener to an editable HTML element to handle composition text insert actions.
   */
  addCompositionTextEventListener() {
    const editableElement = this.getEditableElementRef();
    if (editableElement) {
      editableElement.addEventListener('compositionstart', this.handleCompositionStart);
      editableElement.addEventListener('compositionend', this.handleCompositionEnd);
    }
    this.mutationObserver = new MutationObserver(this.handleObserver);
    this.initMutationObserver();
  }
  /**
   * Removes event listener to an editable HTML element to handle composition text insert actions.
   */
  removeCompositionTextEventListener() {
    const editableElement = this.getEditableElementRef();
    if (editableElement) {
      editableElement.removeEventListener('compositionstart', this.handleCompositionStart);
      editableElement.removeEventListener('compositionend', this.handleCompositionEnd);
    }
    this.removeObserver();
  }
  /**
   * re-connect the observer after the props change and component did render
   */
  reConnectObserver() {
    this.initMutationObserver();
  }
  /**
   * Insert text to a line break node need a special logic if the line break has a next text node.
   *
   * @param {RTETextNode} currentNode The current line break node, the text value is \n
   */
  appendLineBreakNode(currentNode) {
    const textBlock = currentNode.parent;
    const index = textBlock.children.indexOf(currentNode);
    if (textBlock.children[index + 1]) {
      const newTextNode = currentNode.cloneWithText('\n');
      textBlock.apply(new InsertChildrenBeforeAction(textBlock.children[index + 1], newTextNode));
    }
  }
  /**
   * Updates the text content of a rich text node and handles line breaks.
   *
   * @param {RTETextNode} richTextNode - The current rich text node.
   * @param {string} newValue - The target element textContent
   * @param {Nullable<string>} oldValue - The target element old textContent
   * @returns {Nullable<boolean>} The node text is updated or not
   */
  updateCurrentNodeText(richTextNode, newValue, oldValue) {
    const insertText = this.removeZeroWidthSpace(newValue.replace(/(\n)$/, ''));
    if (richTextNode.text !== insertText) {
      const { startOffset } = this.selectionController.getCurrentRange();
      const currentIsLineBreakNode = richTextNode.text === '\n';
      richTextNode.apply(new UpdateTextAction(insertText));
      if (currentIsLineBreakNode) {
        this.appendLineBreakNode(richTextNode);
      }
      const lengthGap = oldValue ? oldValue.length - newValue.length : 0;
      const newOffset = Math.min(insertText.length, startOffset - lengthGap);
      this.selectionController.enqueueSelectionRangeFutureState(richTextNode, Math.max(0, newOffset));
      return true;
    }
  }
  /**
   * The function `getEditableElementRef` returns a reference to the editable HTMLDivElement within a rich text editor.
   *
   * @returns {Nullable<HTMLDivElement>} A reference to an HTMLDivElement element that is editable.
   */
  getEditableElementRef() {
    if (!this.editableElementRef) {
      this.editableElementRef = this.vegaRichTextEditorRenderer.getRTEEditableElementRef();
    }
    return this.editableElementRef;
  }
  /**
   * Remove the ZERO_WIDTH_SPACE from the text.
   *
   * @param {string} text The input text that could include ZERO_WIDTH_SPACE.
   * @returns {string} The result text.
   */
  removeZeroWidthSpace(text) {
    if (text.startsWith(ZERO_WIDTH_SPACE)) {
      return text.slice(ZERO_WIDTH_SPACE.length);
    }
    else if (text.endsWith(ZERO_WIDTH_SPACE)) {
      return text.slice(0, text.length - ZERO_WIDTH_SPACE.length);
    }
    return text;
  }
  /**
   * Dispatch a insert text event to handle the composition text insert logic.
   *
   * @param {string} text - The text need to insert.
   */
  dispatchInsertTextEvent(text) {
    const inputEvent = new CustomEvent('beforeinput');
    inputEvent['data'] = text;
    inputEvent['inputType'] = 'insertText';
    this.editableElementRef.dispatchEvent(inputEvent);
  }
}
__decorate([
  MapToComponentField()
], InsertCompositionTextController.prototype, "selectionController", void 0);
__decorate([
  MapToComponentField()
], InsertCompositionTextController.prototype, "host", void 0);
__decorate([
  MapToComponentField()
], InsertCompositionTextController.prototype, "value", void 0);
__decorate([
  MapToComponentField()
], InsertCompositionTextController.prototype, "valueController", void 0);
__decorate([
  MapToComponentField()
], InsertCompositionTextController.prototype, "userInputController", void 0);
__decorate([
  MapToComponentField()
], InsertCompositionTextController.prototype, "vegaRichTextEditorRenderer", void 0);
__decorate([
  MapToComponentMethod('componentDidLoad')
], InsertCompositionTextController.prototype, "addCompositionTextEventListener", null);
__decorate([
  MapToComponentMethod('disconnectedCallback')
], InsertCompositionTextController.prototype, "removeCompositionTextEventListener", null);
__decorate([
  MapToComponentMethod('componentDidRender')
], InsertCompositionTextController.prototype, "reConnectObserver", null);
