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 image from '../../../assets/image';
import { Fragment, h } from '@stencil/core';
import { MapToComponentField } from 'vega-slimmer/core';
import { NodeAnnotationTypeEnum } from '../../../dto/annotations/node-annotation.abstract';
import { ImageUpdateUrlAction } from '../../../dto/actions/image-update-url-action';
import { VisualModeToolbarButtonSlimmer } from './visual-mode-toolbar-button-slimmer.abstract';
import { ModifyContentActionType } from '../../../dto/actions/modify-content-action.abstract';
import { DomNodeSubjectObserverFactory } from '../../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-observer-factory';
import { VegaClick, VegaDropdownClick } from '../../../../../helpers/event-manager/event-id/vega-event-id';
export class ImageToolbarButtonSlimmer extends VisualModeToolbarButtonSlimmer {
  constructor() {
    super({
      icon: 'image',
      tooltip: { text: 'Image' },
    });
    this.insertURLImage = async () => {
      const url = this.normalizeSafeImageUrl(this.insertURLInputRef.value);
      this.applyImageNode(url, 'url');
      await this.insertURLModalRef.modal('hide');
    };
    this.handleDropdownItemClick = async (payload) => {
      switch (payload.detail) {
        case 'upload':
          this.uploadInputRef.click();
          break;
        case 'url':
          this.currentRange = this.selectionController.getCurrentRange();
          this.currentSelectedNodes = this.selectionController.getSelectedNodes();
          this.currentSelectedBlocks = this.selectionController.getSelectedBlocks();
          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
          this.host.parentElement.append(this.insertURLModalRef);
          this.insertURLInputRef.value = '';
          await this.insertURLModalRef.modal('show');
          await this.insertURLInputRef.doFocus();
          break;
        /* istanbul ignore next */
        default:
          break;
      }
      await this.dropdownRef.hide();
    };
    /**
     * The below method is e2e-test covered in
     * @see{module:should-update-url-properly-when-upload-images}
     */
    /* istanbul ignore next */
    this.fileInputChange = (e) => {
      e.stopPropagation();
      const input = e.target;
      if (!input.files.length) {
        return;
      }
      const node = this.applyImageNode(URL.createObjectURL(input.files[0]), 'upload');
      const payload = {
        file: input.files[0],
        sendBackUploadedURLCallback: this.updateNodeURLMap.get(node),
      };
      this.imageInsertedEventEmitter.emit(payload);
      input.value = '';
    };
  }
  renderBtnWrapper(renderBtn) {
    return (h("vega-box", null,
      h("vega-dropdown", { selectType: "none", trigger: "click", alignment: "center", ref: (ref) => {
          this.dropdownRef = ref;
          this.addDropdownObserver(ref);
        } },
        renderBtn({ showArrowIcon: true }),
        h("div", Object.assign({ slot: "items" }, super.preventLostFocus()), this.renderDropdownContent())),
      this.renderUploadInput(),
      this.renderInsertURLModal()));
  }
  isSelected() {
    return false;
  }
  isDisabled() {
    const selectedNodes = this.selectionController.getSelectedNodes();
    const selectedBlock = this.selectionController.getSelectedBlocks()[0];
    return (super.isDisabled() ||
      selectedNodes.some((node) => node.getAnnotationByType(NodeAnnotationTypeEnum.LINK)) ||
      this.shouldDisabledToolbar(selectedBlock, ModifyContentActionType.INSERT_IMAGE_TO_BLOCK));
  }
  renderDropdownContent() {
    return (h(Fragment, null, ImageToolbarButtonSlimmer.items.map((item) => {
      return (h("vega-dropdown-item", { key: item.key, itemKey: item.key }, this.translationSlimmer.t(item.label)));
    })));
  }
  renderUploadInput() {
    return (h("input", { type: "file", style: { display: 'none' }, ref: (node) => (this.uploadInputRef = node), accept: "image/*", onChange: this.fileInputChange }));
  }
  renderInsertURLModal() {
    return (h("vega-modal", { size: 500, backdropColor: "semi", ref: (node) => (this.insertURLModalRef = node) },
      h("div", { slot: "modal-title" }, this.translationSlimmer.t('Image via URL')),
      h("div", { slot: "modal-content" },
        h("vega-input", { placeholder: this.translationSlimmer.t('URL'), ref: (ref) => (this.insertURLInputRef = ref), 
          /* istanbul ignore next */
          // eslint-disable-next-line react/jsx-no-bind
          onKeyDown: async (event) => {
            event.key === 'Enter' && (await this.insertURLImage());
          } })),
      h("vega-flex", { slot: "modal-footer", gap: "size-8", alignItems: "center", justifyContent: "end" },
        h("vega-button", { label: this.translationSlimmer.t('Cancel'), variant: "secondary", ref: (ref) => {
            this.addModalCancelObserver(ref);
          } }),
        h("vega-button", { label: this.translationSlimmer.t('Insert'), ref: (ref) => {
            this.addModalInsertObserver(ref);
          } }))));
  }
  addDropdownObserver(dropdownRef) {
    DomNodeSubjectObserverFactory.addUniqueObserverToNode(dropdownRef, VegaDropdownClick, this.handleDropdownItemClick);
  }
  addModalCancelObserver(buttonRef) {
    DomNodeSubjectObserverFactory.addUniqueObserverToNode(buttonRef, VegaClick, async () => {
      await this.insertURLModalRef.modal('hide');
    });
  }
  addModalInsertObserver(buttonRef) {
    DomNodeSubjectObserverFactory.addUniqueObserverToNode(buttonRef, VegaClick, this.insertURLImage);
  }
  /**
   * The below method is e2e-test covered in
   * @see{module:should-update-url-properly-when-upload-images}
   */
  /* istanbul ignore next */
  applyImageNode(url, type) {
    const node = type === 'url'
      ? this.insertImageController.insertImageToCaretPosition(url, this.currentSelectedBlocks, this.currentSelectedNodes, this.currentRange)
      : this.insertImageController.insertImageToCaretPosition(url);
    if (!this.updateNodeURLMap) {
      this.updateNodeURLMap = new Map();
    }
    this.updateNodeURLMap.set(node, (url) => {
      node.apply(new ImageUpdateUrlAction(url));
    });
    return node;
  }
  normalizeSafeImageUrl(url) {
    try {
      const parsedUrl = new URL(url);
      if (parsedUrl.protocol === 'javascript:') {
        return '';
      }
      // eslint-disable-next-line no-empty
    }
    catch (_error) { }
    return url;
  }
}
(() => {
  VegaInternalIconManager.register({ image: image });
})();
ImageToolbarButtonSlimmer.items = [
  {
    key: 'upload',
    label: 'Upload from computer',
  },
  {
    key: 'url',
    label: 'Insert via URL',
  },
];
__decorate([
  MapToComponentField()
], ImageToolbarButtonSlimmer.prototype, "host", void 0);
__decorate([
  MapToComponentField()
], ImageToolbarButtonSlimmer.prototype, "insertImageController", void 0);
__decorate([
  MapToComponentField()
], ImageToolbarButtonSlimmer.prototype, "imageInsertedEventEmitter", void 0);
__decorate([
  MapToComponentField()
], ImageToolbarButtonSlimmer.prototype, "selectionController", void 0);
