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 { VegaInternalIconManager } from '../../../../../helpers/icon/internal-icon-manager';
import link from '../../../assets/link';
import { h } from '@stencil/core';
import { DomNodeSubjectObserverFactory } from '../../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-observer-factory';
import { VegaChange } from '../../../../../helpers/event-manager/event-id/vega-event-id';
import { MapToComponentField } from 'vega-slimmer/core';
import { LinkAnnotationAction } from '../../../dto/actions/link-annotation-action';
import { NodeAnnotationTypeEnum } from '../../../dto/annotations/node-annotation.abstract';
import { SelectionChangeAction } from '../../../dto/actions/selection-change-action';
import { generateUUID } from '../../../../../utils/misc';
import { waitForComponentDidRender } from '../../../../../helpers/common/wait-for-component-did-render';
import { VisualModeToolbarButtonSlimmer } from './visual-mode-toolbar-button-slimmer.abstract';
export class LinkToolbarButtonSlimmer extends VisualModeToolbarButtonSlimmer {
  constructor() {
    super({
      icon: 'link',
      tooltip: {
        text: 'Link',
      },
    });
    this.handleLinkEditorChange = ({ detail, }) => {
      switch (detail.action) {
        case 'link': {
          const { url, text } = detail.payload;
          const textChanged = text !== this.currentSelectedText;
          const groupKey = generateUUID();
          this.currentSelectedNodes.forEach((node) => {
            node.apply(new SelectionChangeAction(this.currentRange)).apply(new LinkAnnotationAction({
              link: { href: url, groupKey: groupKey },
              newText: textChanged ? text : undefined,
              needMergeNode: textChanged && this.currentSelectedNodes.length > 1,
              type: 'link',
            }));
          });
          return;
        }
      }
    };
  }
  renderBtnWrapper(renderBtn) {
    return (h("div", { class: "toolbar-btn-link-wrapper", ref: (ref) => (this.linkBtnWrapperRef = ref) },
      renderBtn(),
      h("vega-rich-text-link-editor", { resetStatusAfterHide: false, status: "linkEdit", ref: (ref) => {
          if (ref) {
            this.linkEditorRef = ref;
          }
          DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaChange, this.handleLinkEditorChange);
        } })));
  }
  isSelected() {
    return false;
  }
  isDisabled() {
    const selectedNodes = this.selectionController.getSelectedNodes();
    const selectedBlocks = this.selectionController.getSelectedBlocks();
    return (super.isDisabled() ||
      selectedBlocks.length > 1 ||
      selectedNodes.some((node) => {
        var _a;
        return this.shouldDisabledToolbar(node, LinkAnnotationAction.name) ||
          node.getAnnotationByType(NodeAnnotationTypeEnum.LINK) ||
          ((_a = node.getAnnotationByType(NodeAnnotationTypeEnum.CODE)) === null || _a === void 0 ? void 0 : _a.code);
      }));
  }
  onClick() {
    this.currentRange = this.selectionController.getCurrentRange().toNativeRange();
    this.currentSelectedNodes = this.selectionController.getSelectedNodes();
    if (this.currentRange) {
      this.currentSelectedText = this.currentRange.toString();
      if (this.currentSelectedNodes.length > 0) {
        this.linkEditorRef.record = {
          text: this.currentSelectedText,
          url: '',
        };
      }
    }
    // Set target prop and call show method at the first time to make sure showing later than overrides method call focusController.focusOnLastTextNode()
    // Element appender will control the show and hide logic except for the first time.
    if (!this.linkEditorRef.target) {
      this.linkEditorRef.target = this.linkBtnWrapperRef;
      void waitForComponentDidRender(this.linkEditorRef).then(() => {
        void this.linkEditorRef.show();
      });
    }
  }
}
(() => {
  VegaInternalIconManager.register({ link: link });
})();
__decorate([
  MapToComponentField()
], LinkToolbarButtonSlimmer.prototype, "selectionController", void 0);
