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 { RTEImageBlock } from '../../dto/blocks/image-block';
import { generateUUID } from '../../../../utils/misc';
import { AppendChildrenAction } from '../../dto/actions/append-child-nodes-action';
import { RTEImageNode } from '../../dto/nodes/image-node';
import { InsertImageToBlockAction } from '../../dto/actions/insert-image-to-block-action';
import StateEntityRegistry from './state-entity-rendering-registry';
import { DomNodeSubjectObserverFactory } from '../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-observer-factory';
import { VegaInternalRichTextImageClick, VegaInternalRichTextImageDeleteButtonClicked, } from '../../../../helpers/event-manager/event-id/vega-internal-event-id';
import { ImageAnnotationAction } from '../../dto/actions/image-annotation-action';
/** Used to control the insert image tool button actions */
export class InsertImageController extends VegaSlimmer {
  /**
   * Insert a image to current state
   *
   * @param {string} imageUrl The image url
   * @param {RTEBlock[]} selectedBlocks The current selected blocks, if not provided, will get from selectionController
   * @param {RTENode[]} selectedNodes The current selected nodes, if not provided, will get from selectionController
   * @param {RTERange} currentRange The current selected range, if not provided, will get from selectionController
   * @returns {RTEImageNode} RTEImageNode
   */
  insertImageToCaretPosition(imageUrl, selectedBlocks, selectedNodes, currentRange) {
    selectedBlocks || (selectedBlocks = this.selectionController.getSelectedBlocks());
    const imageBlock = new RTEImageBlock(generateUUID());
    const newImageNode = new RTEImageNode(generateUUID(), imageUrl, imageBlock);
    newImageNode.apply(new ImageAnnotationAction('md', ''));
    imageBlock.apply(new AppendChildrenAction([newImageNode]));
    if (selectedBlocks.length < 1 || this.value.children.length < 1) {
      this.value.apply(new AppendChildrenAction([imageBlock]));
      void this.valueController.flushChanges(this.value);
    }
    else {
      const { startOffset } = currentRange || this.selectionController.getCurrentRange();
      selectedNodes || (selectedNodes = this.selectionController.getSelectedNodes());
      selectedBlocks[0].apply(new InsertImageToBlockAction(selectedNodes[0], startOffset, imageBlock));
    }
    this.updateCaretPosition(newImageNode);
    return newImageNode;
  }
  /**
   * Add image selected observer
   */
  registerObserver() {
    this.registerImageSelectedObserver();
  }
  /**
   * remove the observer when component removed
   */
  unRegisterObserver() {
    this.removeImageSelectedObserver();
  }
  /**
   * Updates the caret position to the parent element of a new image node.
   *
   * @param {RTEImageNode} newImageNode - An image node in a rich text editor.
   */
  updateCaretPosition(newImageNode) {
    this.selectionController.enqueueSelectionRangeFutureState(newImageNode, 1);
  }
  /**
   * The current selected node should be current image node after click image.
   */
  registerImageSelectedObserver() {
    const richTextContentRef = this.vegaRichTextEditorRenderer.getRichTextContentRef();
    if (richTextContentRef) {
      DomNodeSubjectObserverFactory.addUniqueObserverToNode(richTextContentRef, VegaInternalRichTextImageClick, (payload) => {
        const range = this.selectionController.getCurrentRange();
        if (!range || range.startContainer !== payload.host || range.startOffset !== 0) {
          const imageNode = StateEntityRegistry.getEntityByDOM(payload.host.querySelector('img'));
          this.selectionController.enqueueSelectionRangeFutureState(imageNode, 0, imageNode, 0, true);
        }
      });
      /*
       * The below method is e2e-test covered in
       * @see{module:vega-rich-text-editor-image-click-delete-button}
       */
      /* istanbul ignore next */
      DomNodeSubjectObserverFactory.addUniqueObserverToNode(richTextContentRef, VegaInternalRichTextImageDeleteButtonClicked, (payload) => {
        const range = this.selectionController.getCurrentRange();
        if (!range || range.startContainer !== payload.host || range.startOffset !== 1) {
          this.selectionController.enqueueSelectionRangeFutureState(payload.host, 1, payload.host, 1, true);
        }
      });
    }
  }
  /**
   * remove the observer after component delete
   */
  removeImageSelectedObserver() {
    const richTextContentRef = this.vegaRichTextEditorRenderer.getRichTextContentRef();
    if (richTextContentRef) {
      DomNodeSubjectObserverFactory.removeUniqueObserverFromNode(richTextContentRef, VegaInternalRichTextImageClick);
      DomNodeSubjectObserverFactory.removeUniqueObserverFromNode(richTextContentRef, VegaInternalRichTextImageDeleteButtonClicked);
    }
  }
}
__decorate([
  MapToComponentField()
], InsertImageController.prototype, "selectionController", void 0);
__decorate([
  MapToComponentField()
], InsertImageController.prototype, "value", void 0);
__decorate([
  MapToComponentField()
], InsertImageController.prototype, "valueController", void 0);
__decorate([
  MapToComponentField()
], InsertImageController.prototype, "vegaRichTextEditorRenderer", void 0);
__decorate([
  MapToComponentMethod('componentDidLoad')
], InsertImageController.prototype, "registerObserver", null);
__decorate([
  MapToComponentMethod('disconnectedCallback')
], InsertImageController.prototype, "unRegisterObserver", null);
