import { ElementIDUtils } from "@sankhyalabs/core";
import { forceUpdate, h } from "@stencil/core";
import ApplicationUtils from "../../utils/ApplicationUtils";
import initI18n from "../../utils/i18n";
import RemoteFile from "./RemoteFile";
export class EzUpload {
  constructor() {
    this._filePointers = new Map();
    this.label = undefined;
    this.subtitle = undefined;
    this.enabled = true;
    this.maxFileSize = undefined;
    this.maxFiles = undefined;
    this.requestHeaders = undefined;
    this.urlUpload = undefined;
    this.urlDelete = undefined;
    this.value = undefined;
  }
  observeValue(newValue, oldValue) {
    //Observamos o mundo externo, se um novo valor foi atribuído,
    //precisamos cancelar a alteração anterior, isso envolve, percorrer
    //a lista de ponteiros e cancelar todos os uploads em andamento.
    if (newValue !== this._updatingValue || (newValue == undefined && oldValue != undefined)) {
      this._filePointers.forEach(f => {
        if (this.isRemoteFile(f)) {
          f.abortUpload();
        }
      });
      this._filePointers = new Map();
      this.updateFilePointers();
      this._updatingValue = undefined;
    }
  }
  updateFilePointers() {
    if (Array.isArray(this.value)) {
      this.value.forEach(ezFile => this._filePointers.set(ezFile.name, ezFile));
    }
  }
  observeRequestHeaders() {
    this._requestHeaders = new Map();
    if (typeof this.requestHeaders == "string") {
      try {
        this.requestHeaders = JSON.parse(this.requestHeaders);
      }
      catch (e) {
        this.requestHeaders = undefined;
      }
    }
    for (var key in this.requestHeaders) {
      this._requestHeaders.set(key, this.requestHeaders[key]);
    }
  }
  /**
   * Adiciona arquivos.
   */
  async addFiles(files) {
    if (this.maxFiles > 0) {
      let countDistinctFiles = this._filePointers.size;
      files.forEach(file => {
        if (!this._filePointers.has(file.name)) {
          countDistinctFiles++;
        }
      });
      if (countDistinctFiles > this.maxFiles) {
        this.showError(this.i18n("ez-upload.maxFilesError", { maxFiles: this.maxFiles }));
        return;
      }
    }
    Array.prototype.forEach.call(files, this.addFile.bind(this));
  }
  /**
   * Aplica o foco no campo.
   */
  async setFocus() {
    this._fileInput.focus();
  }
  /**
   * Remove o foco do campo.
   */
  async setBlur() {
    this._fileInput.blur();
  }
  async addFile(file) {
    const oldFile = this._filePointers.get(file.name);
    if (oldFile) {
      ApplicationUtils.confirm(this.i18n("ez-upload.replaceFileTitle"), this.i18n("ez-upload.replaceFileMessage", { fileName: file.name })).then(ok => {
        if (ok) {
          if (this.isRemoteFile(oldFile)) {
            oldFile.abortUpload();
          }
          this.doAddFile(file);
        }
      });
    }
    else {
      this.doAddFile(file);
    }
  }
  async doAddFile(file) {
    try {
      if (this.validateFile(file)) {
        this.ezStartChange.emit({
          waitmessage: this.i18n("ez-upload.uploadingMessage"),
          blocking: true
        });
        const uploadingFile = new RemoteFile(file);
        const oldPointer = this._filePointers.get(file.name);
        if (oldPointer && this.isRemoteFile(oldPointer)) {
          oldPointer.abortUpload();
        }
        this._filePointers.set(file.name, uploadingFile);
        uploadingFile.upload(this.urlUpload, this._requestHeaders, (file) => this.updateFeedback(file))
          .then((files) => files.forEach(ezFile => this.finishUpload(uploadingFile.name, ezFile)))
          .catch(msg => {
          this.ezCancelWaitingChange.emit();
          this.showError(msg);
        });
        forceUpdate(this);
      }
    }
    catch (error) {
      this.ezCancelWaitingChange.emit();
      throw error;
    }
  }
  finishUpload(key, ezFile) {
    this._filePointers.set(key, ezFile);
    this.updateValue();
  }
  updateValue() {
    this._updatingValue = [];
    this._filePointers.forEach(f => {
      if (!this.isRemoteFile(f)) {
        this._updatingValue.push(f);
      }
    });
    if (this._filePointers.size === this._updatingValue.length) {
      this.value = this._updatingValue;
      this.ezChange.emit(this.value);
    }
  }
  buildProgressId(uploading) {
    let sanitizedName = uploading.name.replace(/[^a-z0-9_]/gi, "_");
    return `PROGRESS_${sanitizedName}_${uploading.file.lastModified}`;
  }
  updateFeedback(uf) {
    window.requestAnimationFrame(() => {
      if (this._host) {
        const progress = this._host.shadowRoot.querySelector("#" + this.buildProgressId(uf));
        if (progress) {
          progress.value = uf.progress;
        }
      }
    });
  }
  validateFile(file) {
    if (!this._filePointers.has(file.name) && this.maxFiles > 0 && this._filePointers.size >= this.maxFiles) {
      this.showError(this.i18n("ez-upload.maxFilesError", { maxFiles: this.maxFiles }));
      return false;
    }
    if (file.size === 0) {
      this.showError(this.i18n("ez-upload.emptyFileError", { fileName: file.name }));
      return false;
    }
    if (!this.urlUpload) {
      this.showError(this.i18n("ez-upload.missingUploadUrlError"));
      return false;
    }
    if (this.maxFileSize >= 0 && file.size > this.maxFileSize) {
      this.showError(this.i18n("ez-upload.maxFileSizeError", { maxSize: this.formatBytes(this.maxFileSize) }));
      return false;
    }
    return true;
  }
  showError(message) {
    ApplicationUtils.alert(this.i18n("ez-upload.uploadErrorTitle"), message);
  }
  formatBytes(bytes, decimals = 1) {
    if (bytes === 0)
      return "0 Bytes";
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
  }
  onFileInputChange(event) {
    const input = event.target;
    this.addFiles(Array.from(input.files));
    this._fileInput.value = "";
  }
  isRemoteFile(item) {
    return "file" in item;
  }
  removeFromList(name) {
    this._filePointers.delete(name);
    this.updateValue();
  }
  removeFile(name) {
    const item = this._filePointers.get(name);
    if (this.isRemoteFile(item)) {
      item.abortUpload();
      this.removeFromList(name);
    }
    else {
      if (this.urlDelete) {
        const uploadingFile = new RemoteFile(null);
        this._filePointers.set(item.name, uploadingFile);
        uploadingFile.delete(item, this.urlDelete, null)
          .then(_ok => this.removeFromList(name))
          .catch(msg => this.showError(msg));
      }
      else {
        this.removeFromList(name);
      }
    }
  }
  openFilesDialog() {
    if (this.enabled) {
      this._fileInput.click();
    }
  }
  componentDidLoad() {
    if (this.enabled && this._dropZone && window.FileList && window.File) {
      this._dropZone.addEventListener("dragover", event => {
        event.stopPropagation();
        event.preventDefault();
        event.dataTransfer.dropEffect = "copy";
        this._dropZone.style.background = "#c2dbff";
      });
      this._dropZone.addEventListener("drop", event => {
        event.stopPropagation();
        event.preventDefault();
        this.addFiles(Array.from(event.dataTransfer.files));
        this._dropZone.style.background = "";
      });
      this._dropZone.addEventListener("dragleave", _event => {
        this._dropZone.style.background = "";
      });
    }
    if (this._host) {
      ElementIDUtils.addIDInfo(this._host, 'input');
    }
    this.observeRequestHeaders();
  }
  componentWillRender() {
    if (this.value) {
      if (this._filePointers.size < this.value.length) {
        this.updateFilePointers();
      }
    }
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  render() {
    return (h("div", { ref: (el) => this._dropZone = el, class: this.evalDisabledClass("iu", "background--disabled") }, h("div", { class: "iu__container", onClick: () => this.openFilesDialog() }, h("div", { class: "iu_header" }, this.label ? h("label", { class: this.evalDisabledClass("iu__label", "text--disabled"), title: this.label }, this.label) : null, h("div", { class: "padding-large" }, h("div", { class: this.evalDisabledClass("iu__icon-label", "mouse-pointer--disabled") }, h("button", { class: "iu__file-icon", disabled: !this.enabled }), h("div", { class: this.evalDisabledClass("text text--center text--medium text--primary", "text--disabled") }, this.enabled ? this.i18n("ez-upload.enable") : this.i18n("ez-upload.disable"))), this.subtitle &&
      h("div", { class: this.evalDisabledClass("padding-extra-small text text--center text--small text--secondary", "text--disabled") }, this.subtitle))), this.buildFooter()), h("input", { ref: (el) => this._fileInput = el, onChange: (ev) => this.onFileInputChange(ev), type: "file", multiple: true, class: "appearanceNone" })));
  }
  buildFooter() {
    if (this._filePointers.size === 0) {
      return null;
    }
    const items = [];
    this._filePointers.forEach(item => items.push(this.buildFileItem(item)));
    return (h("div", { class: "iu__footer" }, items));
  }
  buildFileItem(item) {
    const fileName = item.name;
    const progress = Number(item["progress"]);
    const downloadURL = item["downloadURL"];
    const size = item.size > 0 ? `(${this.formatBytes(item.size)})` : '';
    const label = `${fileName} ${size}`;
    return (h("div", { class: "iu__item", key: fileName, onClick: evt => evt.stopPropagation() }, h("div", { class: "iu__item-label modificador" }, h("div", { title: label, class: "col--stretch align--middle file__name text text--primary text--small text--ellipsis align--middle" }, downloadURL ? h("a", { href: downloadURL, download: true }, label) : label)), isNaN(progress)
      ?
        null
      :
        h("div", { class: "col col--sd-4 col--stretch align--middle" }, h("progress", { id: this.buildProgressId(item), value: progress, max: "100" })), this.enabled
      ?
        h("div", { class: "col col--stretch align--middle" }, h("button", { class: "btn-cancel ", onClick: () => this.removeFile(fileName) }))
      :
        null));
  }
  evalDisabledClass(regularClasses, disabledClass) {
    return this.enabled ? regularClasses : `${regularClasses} ${disabledClass}`;
  }
  static get is() { return "ez-upload"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-upload.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-upload.css"]
    };
  }
  static get properties() {
    return {
      "label": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Texto a ser apresentado como t\u00EDtulo do campo."
        },
        "attribute": "label",
        "reflect": false
      },
      "subtitle": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o subt\u00EDtulo utilizado no campo de upload"
        },
        "attribute": "subtitle",
        "reflect": false
      },
      "enabled": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se false o usu\u00E1rio n\u00E3o pode interagir com o campo."
        },
        "attribute": "enabled",
        "reflect": false,
        "defaultValue": "true"
      },
      "maxFileSize": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o tamanho m\u00E1ximo (em bytes) de cada arquivo que pode ser transferido"
        },
        "attribute": "max-file-size",
        "reflect": false
      },
      "maxFiles": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define um limite para a quantidade de arquivos"
        },
        "attribute": "max-files",
        "reflect": false
      },
      "requestHeaders": {
        "type": "any",
        "mutable": false,
        "complexType": {
          "original": "any",
          "resolved": "any",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Headers para a requisi\u00E7\u00E3o Http"
        },
        "attribute": "request-headers",
        "reflect": false
      },
      "urlUpload": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a URL de upload"
        },
        "attribute": "url-upload",
        "reflect": false
      },
      "urlDelete": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a URL de dele\u00E7\u00E3o"
        },
        "attribute": "url-delete",
        "reflect": false
      },
      "value": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "Array<EzFile>",
          "resolved": "EzFile[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "EzFile": {
              "location": "local"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o valor do campo."
        }
      }
    };
  }
  static get events() {
    return [{
        "method": "ezChange",
        "name": "ezChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando acontece a altera\u00E7\u00E3o de valor do campo."
        },
        "complexType": {
          "original": "Array<EzFile>",
          "resolved": "EzFile[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "EzFile": {
              "location": "local"
            }
          }
        }
      }, {
        "method": "ezStartChange",
        "name": "ezStartChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido ao iniciar a altera\u00E7\u00E3o (remover ou adicionar um arquivo)."
        },
        "complexType": {
          "original": "WaitingChange",
          "resolved": "WaitingChange",
          "references": {
            "WaitingChange": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        }
      }, {
        "method": "ezCancelWaitingChange",
        "name": "ezCancelWaitingChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando n\u00E3o foi poss\u00EDvel completar a altera\u00E7\u00E3o entre o evento ezStartChange e ezChange."
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "addFiles": {
        "complexType": {
          "signature": "(files: Array<File>) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "Array": {
              "location": "global"
            },
            "File": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Adiciona arquivos.",
          "tags": []
        }
      },
      "setFocus": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Aplica o foco no campo.",
          "tags": []
        }
      },
      "setBlur": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Remove o foco do campo.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_host"; }
  static get watchers() {
    return [{
        "propName": "value",
        "methodName": "observeValue"
      }, {
        "propName": "requestHeaders",
        "methodName": "observeRequestHeaders"
      }];
  }
}
