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 { h } from '@stencil/core';
import CodeFormatter from '../../../../helpers/code-format/code-formatter';
import { DomNodeSubjectObserverFactory } from '../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-observer-factory';
import { VegaInternalCodeBlockBlur } from '../../../../helpers/event-manager/event-id/vega-internal-event-id';
import { VegaRTEContent } from '../../dto/content-state';
/**
 * The renderer for the source view of the rich text editor. It renders a code block for editing the source code of the rich text editor content.
 */
export class VegaRichTextEditorSourceViewRenderer extends VegaSlimmer {
  constructor() {
    super(...arguments);
    this.prevRecord = '';
    /**
     * Handle the blur event of the code block. When the code block loses focus, emit the source code change event with the current source code.
     */
    this.handleCodeBlockBlur = () => {
      var _a;
      // If source view is closed while blurring, it means the user switch back to normal mode, so we can skip emitting the change event.
      if (this.sourceView) {
        const filterInlineStyles = Boolean(this.sourceEditConfig.filterInlineStyles);
        const sourceCode = this.getSourceCode();
        const newValue = VegaRTEContent.fromHtml(sourceCode, {
          autoMatchFormat: (_a = this.sourceEditConfig.autoMatchFormat) !== null && _a !== void 0 ? _a : true,
          filterInlineStyles,
        });
        const newSourceCode = newValue.toHtml({ filterInlineStyles });
        if (newSourceCode !== this.prevRecord) {
          this.sourceCodeChangeEventEmitter.emit(newSourceCode);
          this.prevRecord = newSourceCode;
        }
      }
    };
  }
  /**
   * Clean up the code block blur observer when the component is disconnected to prevent memory leaks.
   */
  clearCodeBlockBlurObserver() {
    if (this.sourceCodeBlockRef) {
      DomNodeSubjectObserverFactory.removeUniqueObserverFromNode(this.sourceCodeBlockRef, VegaInternalCodeBlockBlur);
    }
  }
  /**
   * Get the source code from the source view's code block.
   *
   * @returns {Nullable<string>} The source code, or null if the code block reference is not set.
   */
  getSourceCode() {
    if (this.sourceCodeBlockRef) {
      return this.sourceCodeBlockRef.value.code;
    }
  }
  /**
   * Render the source view, which is a code block for editing the source code of the rich text editor content.
   *
   * @returns {Nullable<HTMLElement>} The rendered source view element, or null if source editing is not allowed.
   */
  render() {
    if (!this.allowSourceEdit)
      return;
    const sourceCode = this.getSourceTemplate();
    const sourceViewValue = this.sourceView ? CodeFormatter.format(sourceCode) : '';
    // Record the source view value when rendering, which will be used to compare with the current source view value when blurring the code block to determine whether to emit the source code change event.
    this.prevRecord = sourceCode;
    return (h("div", { class: {
        'source-view-container': true,
        'vega-hidden': !this.sourceView,
      } },
      h("vega-code-block", { ref: (ref) => {
          this.sourceCodeBlockRef = ref;
          DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaInternalCodeBlockBlur, this.handleCodeBlockBlur);
        }, disabled: this.disabled, value: { language: 'html', code: sourceViewValue } })));
  }
  /**
   * Get the source view template string based on the current value of the rich text editor.
   *
   * @returns {string} The HTML template string
   */
  getSourceTemplate() {
    return this.value.toHtml({ filterInlineStyles: this.sourceEditConfig.filterInlineStyles });
  }
}
__decorate([
  MapToComponentField()
], VegaRichTextEditorSourceViewRenderer.prototype, "host", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextEditorSourceViewRenderer.prototype, "allowSourceEdit", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextEditorSourceViewRenderer.prototype, "sourceView", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextEditorSourceViewRenderer.prototype, "value", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextEditorSourceViewRenderer.prototype, "disabled", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextEditorSourceViewRenderer.prototype, "sourceEditConfig", void 0);
__decorate([
  MapToComponentField()
], VegaRichTextEditorSourceViewRenderer.prototype, "sourceCodeChangeEventEmitter", void 0);
__decorate([
  MapToComponentMethod('disconnectedCallback')
], VegaRichTextEditorSourceViewRenderer.prototype, "clearCodeBlockBlurObserver", null);
