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 { MapToComponentField, MapToComponentMethod, VegaSlimmer } from 'vega-slimmer/core';
import changeManager from '../../../../helpers/change-manager/change-manager';
import { FORM_ELEMENT_VALUE_CHANGE } from '../../../../helpers/change-manager/subject/static-subject/static-subject-title';
import ChangeManager from '../../../../helpers/change-manager/change-manager';
import domNodeSubjectFactory from '../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-factory';
import { VegaInternalRichTextEditorFlushChanges } from '../../../../helpers/event-manager/event-id/vega-internal-event-id';
import { Observer } from '../../../../helpers/change-manager/observer/observer';
import { debounce } from '../../../../utils/timer';
import { VegaRTEContent } from '../../dto/content-state';
import { waitForComponentDidRender } from '../../../../helpers/common/wait-for-component-did-render';
import { RTEEditorState } from '../../dto/editor-state';
import { RTESelectionState } from '../../dto/selection-state';
import stateEntityRenderingRegistry from './state-entity-rendering-registry';
/**
 * The value controller is responsible for updating the value of the rich text editor.
 */
export class ValueController extends VegaSlimmer {
  /**
   * Component lifecycle - [connectedCallback]{@link VegaRichTextEditor.connectedCallback}
   */
  connectedCallback() {
    const flushChangesWithDebounce = debounce(() => {
      void this.valueController.flushChanges(this.value);
    }, ValueController.VALUE_CHANGE_DEBOUNCE_TIME, this);
    this.flushChangeObserver = new Observer(this.isAcceptableFlushChange.bind(this), flushChangesWithDebounce);
    ChangeManager.register(domNodeSubjectFactory.getSubject(this.host, VegaInternalRichTextEditorFlushChanges), this.flushChangeObserver);
  }
  /**
   * Component lifecycle - [connectedCallback]{@link VegaRichTextEditor.disconnectedCallback}
   */
  disconnectedCallback() {
    ChangeManager.unregister(domNodeSubjectFactory.getSubject(this.host, VegaInternalRichTextEditorFlushChanges), this.flushChangeObserver);
  }
  /**
   * Component lifecycle - [componentWillLoad]{@link VegaRichTextEditor.componentWillLoad}
   */
  componentWillLoad() {
    if (this.value && !(this.value instanceof VegaRTEContent)) {
      this.value = VegaRTEContent.fromJSON(this.value);
    }
    this.registerEditorRefAndContent();
  }
  /**
   * Watches the value of the editor and updates the internal value.
   */
  watchValueUpdate() {
    const autoMatchFormat = this.sourceEditConfig.autoMatchFormat;
    if (this.value && !(this.value instanceof VegaRTEContent)) {
      this.value = VegaRTEContent.fromJSON(this.value, { autoMatchFormat });
    }
    else if (!this.value || this.value.children.length === 0) {
      this.value = VegaRTEContent.createEmptyContent({ autoMatchFormat });
    }
    else {
      this.changeEventEmitter.emit(this.value);
      changeManager.notify(FORM_ELEMENT_VALUE_CHANGE, {
        host: this.host,
        detail: this.value,
      });
    }
    this.registerEditorRefAndContent();
  }
  /**
   * Updates the value of the editor and restore the selection.
   *
   * @param {VegaRTEContent} newValue The new value to set.
   * @param {boolean} recordHistory - Whether to record the change in history.
   */
  async flushChanges(newValue, recordHistory = true) {
    this.value = newValue.clone();
    if (recordHistory) {
      this.historyController.registerHistory(new RTEEditorState(this.value, new RTESelectionState(this.selectionController.getCurrentRange())));
    }
    await waitForComponentDidRender(this.host);
  }
  /**
   * Determines whether the observer should accept changes.
   *
   * @returns {boolean} Always returns true in the current implementation.
   */
  isAcceptableFlushChange() {
    return true;
  }
  /**
   * Register the host element and the current content.
   */
  registerEditorRefAndContent() {
    if (this.host && this.host.value) {
      stateEntityRenderingRegistry.register(this.host, this.host.value);
    }
  }
}
ValueController.VALUE_CHANGE_DEBOUNCE_TIME = 50;
__decorate([
  MapToComponentField()
], ValueController.prototype, "host", void 0);
__decorate([
  MapToComponentField({ writable: true })
], ValueController.prototype, "value", void 0);
__decorate([
  MapToComponentField()
], ValueController.prototype, "changeEventEmitter", void 0);
__decorate([
  MapToComponentField()
], ValueController.prototype, "valueController", void 0);
__decorate([
  MapToComponentField()
], ValueController.prototype, "historyController", void 0);
__decorate([
  MapToComponentField()
], ValueController.prototype, "selectionController", void 0);
__decorate([
  MapToComponentField()
], ValueController.prototype, "sourceEditConfig", void 0);
__decorate([
  MapToComponentMethod('connectedCallback')
], ValueController.prototype, "connectedCallback", null);
__decorate([
  MapToComponentMethod('disconnectedCallback')
], ValueController.prototype, "disconnectedCallback", null);
__decorate([
  MapToComponentMethod('componentWillLoad')
], ValueController.prototype, "componentWillLoad", null);
__decorate([
  MapToComponentMethod('watchValueUpdate')
], ValueController.prototype, "watchValueUpdate", null);
