import { Fragment, h } from "@stencil/core";
import { RICH_TOOLBAR_COMMANDS } from "../ez-rich-toolbar/RichToolbarHelper";
import { formatBytes } from "./utils/formatBytes";
import { fileToBase64 } from "./utils/fileToBase64";
import initI18n from '../../../utils/i18n';
export class EzSimpleImageUploader {
  constructor() {
    this.link = undefined;
    this.base64 = undefined;
    this.messageError = undefined;
    this.selectedFile = undefined;
    this.maxSize = 500;
  }
  /**
  * Método responsável pela abertura do popup.
  */
  async show() {
    this._popupElement.opened = true;
  }
  /**
  * Método responsável pelo fechamento do popup.
  */
  async hide() {
    this._popupElement.opened = false;
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  async handleCancel() {
    this.removeSelectedFile();
    this.executeToolbarCommand.emit({ command: RICH_TOOLBAR_COMMANDS.FOCUS });
    await this.hide();
  }
  removeSelectedFile(event) {
    event === null || event === void 0 ? void 0 : event.stopPropagation();
    this.link = undefined;
    this.base64 = undefined;
    this.selectedFile = undefined;
    this.messageError = undefined;
  }
  triggerFileSelect() {
    if (!this.selectedFile) {
      this._fileInput.click();
    }
  }
  async handleImage(files) {
    const file = files && files[0];
    if (!file) {
      return;
    }
    if (file.size < (this.maxSize * 1000)) {
      this.selectedFile = file;
      this.base64 = await fileToBase64(file);
    }
    else {
      this.messageError = this.i18n("ez-simple-image-uploader.imageTooLarge", { maxSize: formatBytes(this.maxSize) });
    }
  }
  getFileList(event) {
    if (event instanceof DragEvent) {
      return Array.from(event.dataTransfer.files);
    }
    else {
      const input = event.target;
      return input.files;
    }
  }
  handleFileChange(event) {
    event.preventDefault();
    this.messageError = undefined;
    this._dropZone.classList.remove("dragging");
    const files = this.getFileList(event);
    this.handleImage(files);
    const input = event.target;
    input.value = "";
  }
  handleDragOver(event) {
    event.stopPropagation();
    event.preventDefault();
  }
  handleDragEnter(event) {
    event.preventDefault();
    this._dropZone.classList.add("dragging");
  }
  handleDragLeave(event) {
    event.preventDefault();
    if (!this._dropZone.contains(event.relatedTarget)) {
      this._dropZone.classList.remove("dragging");
    }
  }
  async handleActionPopup(event) {
    if (event.detail === "OK") {
      await this.handleCreateImgTag();
    }
    else if (event.detail === "CANCEL" || event.detail === "CLOSE") {
      await this.handleCancel();
    }
  }
  async handleCreateImgTag() {
    var _a;
    const tag = `<img src="${(_a = this.base64) !== null && _a !== void 0 ? _a : this.link}" alt="${this.i18n("ez-simple-image-uploader.imageAlt")}" />`;
    this.executeToolbarCommand.emit({ command: RICH_TOOLBAR_COMMANDS.FORMAT, value: tag });
    this.removeSelectedFile();
    await this.hide();
  }
  getOkButtonStatus() {
    var _a;
    return (!this.base64 && !((_a = this.link) === null || _a === void 0 ? void 0 : _a.trim())) ? 'DISABLED' : 'ENABLED';
  }
  render() {
    return (h("ez-popup", { ref: ref => this._popupElement = ref, heightMode: "auto", size: "small", useHeader: false, onEzClosePopup: () => this.handleCancel() }, h("div", null, h("ez-modal-container", { modalTitle: this.i18n("ez-simple-image-uploader.uploadTitle"), modalSubTitle: this.i18n("ez-simple-image-uploader.uploadSubtitle"), okButtonLabel: this.i18n("ez-simple-image-uploader.submit"), cancelButtonLabel: this.i18n("app.cancel"), onEzModalAction: this.handleActionPopup.bind(this), okButtonStatus: this.getOkButtonStatus() }, h("div", { class: "image-uploader-container" }, h("ez-tooltip", { message: this.i18n("ez-simple-image-uploader.tooltipMessage"), active: !!this.selectedFile }, h("ez-text-input", { label: this.i18n("ez-simple-image-uploader.urlInputLabel"), value: this.link, onEzChange: (e) => this.link = e.detail, enabled: !this.selectedFile })), h("span", null, this.i18n("ez-simple-image-uploader.orText")), h("section", { class: "drop-zone-section" }, h("div", { ref: (ref) => this._dropZone = ref, class: "drop-zone", onDrop: (ev) => this.handleFileChange(ev), onDragOver: (ev) => this.handleDragOver(ev), onDragEnter: (ev) => this.handleDragEnter(ev), onDragLeave: (ev) => this.handleDragLeave(ev) }, h("div", { class: {
        "drop-zone-container": true,
        "clickable": !this.selectedFile,
      }, onClick: () => this.triggerFileSelect() }, !!this.selectedFile ?
      h(Fragment, null, h("span", { class: "ez-text ez-text--primary ez-text--medium" }, this.selectedFile.name, " (", formatBytes(this.selectedFile.size), ")"), h("button", { class: "button-close", onClick: (event) => this.removeSelectedFile(event), title: this.i18n("ez-simple-image-uploader.removeFile") }, h("ez-icon", { iconName: "close" })))
      :
        h(Fragment, null, h("ez-icon", { iconName: "anexo" }), h("span", { class: "ez-text ez-text--primary ez-text--medium" }, this.i18n("ez-simple-image-uploader.dragDropText")))), h("input", { ref: (el) => this._fileInput = el, type: "file", accept: "image/*", style: { display: "none" }, onChange: (ev) => this.handleFileChange(ev) })), !!this.messageError && h("span", { class: "text-error" }, this.messageError)))))));
  }
  static get is() { return "ez-simple-image-uploader"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-simple-image-uploader.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-simple-image-uploader.css"]
    };
  }
  static get properties() {
    return {
      "maxSize": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Tamanho m\u00E1ximo que a imagem poder\u00E1 ter em kilobytes."
        },
        "attribute": "max-size",
        "reflect": false,
        "defaultValue": "500"
      }
    };
  }
  static get states() {
    return {
      "link": {},
      "base64": {},
      "messageError": {},
      "selectedFile": {}
    };
  }
  static get events() {
    return [{
        "method": "executeToolbarCommand",
        "name": "executeToolbarCommand",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "RichToolbarCommand",
          "resolved": "RichToolbarCommand",
          "references": {
            "RichToolbarCommand": {
              "location": "import",
              "path": "../ez-rich-toolbar/RichToolbarHelper"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "show": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "M\u00E9todo respons\u00E1vel pela abertura do popup.",
          "tags": []
        }
      },
      "hide": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "M\u00E9todo respons\u00E1vel pelo fechamento do popup.",
          "tags": []
        }
      }
    };
  }
}
