'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-a7b0c73d.js');
const core = require('@sankhyalabs/core');
const ApplicationUtils = require('./ApplicationUtils-5cc05979.js');
const index$1 = require('./index-1be40f19.js');
require('./DialogType-2114c337.js');

class RemoteFile {
  constructor(file) {
    this.file = file;
    this.size = file.size;
    this.name = file.name;
  }
  abortUpload() {
    if (this._uploadingXhr) {
      this._aborted = true;
      this._uploadingXhr.abort();
      this._uploadingXhr = undefined;
    }
  }
  isUploading() {
    return this._uploadingXhr !== undefined;
  }
  async upload(server, headers, updateCallBack) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      this._uploadingXhr = xhr;
      this._aborted = false;
      this.progress = 0;
      xhr.upload.onprogress = (e) => {
        const loaded = e.loaded;
        const total = e.total;
        this.progress = ~~((loaded / total) * 100);
        updateCallBack(this, loaded, total);
      };
      xhr.onreadystatechange = () => {
        if (xhr.readyState == 4) {
          this._uploadingXhr = undefined;
          const status = xhr.status;
          if (!this._aborted) {
            if (status === 0) {
              reject("Servidor indisponível");
            }
            else if (status >= 500) {
              reject("Erro inesperado no servidor");
            }
            else if (status >= 400) {
              reject("Operação não permitida");
            }
          }
          const response = xhr.response;
          if (response) {
            try {
              resolve(JSON.parse(response));
            }
            catch (error) {
              reject(`Servidor não retornou um objeto válido: ${response}.\n${error}`);
            }
          }
        }
      };
      xhr.ontimeout = () => {
        reject("Tempo limite de transferência atingido.");
      };
      const formData = new FormData();
      formData.append("ARQUIVO", this.file, this.file.name);
      xhr.open("POST", server, true);
      if (headers) {
        headers.forEach((value, key) => xhr.setRequestHeader(key, value));
      }
      xhr.send(formData);
    });
  }
  async delete(item, server, headers) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = () => {
        if (xhr.readyState == 4) {
          if (xhr.status === 0) {
            reject("Servidor indisponível");
          }
          else if (xhr.status >= 500) {
            reject("Erro inesperado no servidor");
          }
          else if (xhr.status >= 400) {
            reject("Operação não permitida");
          }
          resolve(true);
        }
      };
      xhr.ontimeout = () => {
        reject("Tempo limite de remoção atingido.");
      };
      xhr.open("DELETE", server, true);
      if (headers) {
        headers.forEach((value, key) => xhr.setRequestHeader(key, value));
      }
      xhr.send(JSON.stringify(item));
    });
  }
}

const ezUploadCss = ":host{--ez-upload--height:42px;--ez-upload--width:100%;--ez-upload__icon--width:48px;--ez-upload__container--background-color:var(--background--medium, #d2dce9);--ez-upload__color--primary:var(--color--primary, #008561);--ez-upload--padding--extra-small:var(--space--extra-small, 3px);--ez-upload--padding--small:var(--space--small, 6px);--ez-upload--padding--medium:var(--space--medium, 12px);--ez-upload--padding--large:var(--space--large, 24px);--ez-upload__border--color:var(--color-strokes, #DCE0E8);--ez-upload--text-shadow:var(--text-shadow, 0 0 0 #353535, 0 0 1px transparent);--ez-upload--text--primary:var(--text-primary, #626e82);--ez-upload--text--secondary:var(--text-secondary, #a2abb9);--ez-upload--font-size:var(--text--medium, 14px);--ez-upload--font-family:var(--font-pattern, Arial);--ez-upload--font-weight:var(--text-weight--large, 500);--ez-upload__btn__cancel-image:url('data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" height=\"8x\" width=\"8px\"><path d=\"M 8,0.8 7.2,0 4,3.2 0.8,0 0,0.8 3.2,4 0,7.2 0.8,8 4,4.8 7.2,8 8,7.2 4.8,4 Z\"/></svg>');--ez-upload__file-icon-image:url('data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" height=\"11x\" width=\"9px\"><path d=\"M 1.2272719,8.4999999 V 2.75 c 0,-1.1045695 1.4652499,-2 3.2727273,-2 1.8074777,0 3.2727281,0.8954305 3.2727281,2 V 8.9999999 C 7.7727273,9.690356 6.8569456,10.25 5.7272719,10.25 4.5975985,10.25 3.6818174,9.690356 3.6818174,8.9999999 V 3.75 c 0,-0.2761425 0.3663125,-0.5 0.8181818,-0.5 0.4518694,0 0.8181818,0.2238575 0.8181818,0.5 V 8.4999999 H 6.5454537 V 3.75 C 6.5454537,3.059644 5.6296725,2.5 4.4999992,2.5 3.3703258,2.5 2.4545446,3.059644 2.4545446,3.75 V 8.9999999 C 2.4545446,10.10457 3.9197945,11 5.7272719,11 7.5347496,11 9,10.10457 9,8.9999999 V 2.75 C 9,1.231217 6.9852809,0 4.4999992,0 2.0147181,5e-7 0,1.231217 0,2.75 v 5.7499999 z\"/></svg>');display:flex;flex-wrap:wrap;position:relative;padding-bottom:16px;font-family:var(--ez-upload--font-family);font-size:var(--ez-upload--font-size);width:var(--ez-upload--width);font-weight:var(--ez-upload--font-weight)}.iu{display:flex;flex-wrap:wrap;background-color:var(--ez-upload__container--background-color);padding:var(--ez-upload--padding--small);width:100%;border-radius:12px;box-sizing:border-box}.iu__container{width:100%;display:flex;flex-wrap:wrap;justify-content:center;align-items:center;border:2px dashed var(--ez-upload__border--color);border-radius:6px;box-sizing:border-box}.iu__footer{display:flex;flex-wrap:wrap;justify-content:flex-start;width:100%;padding:0 var(--ez-upload--padding--medium) var(--ez-upload--padding--medium) var(--ez-upload--padding--medium);box-sizing:border-box}.iu__item{display:flex;width:100%;justify-content:flex-start;align-items:center;align-self:center;padding-bottom:var(--ez-upload--padding--extra-small);box-sizing:border-box;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.iu__item-label{display:flex;max-width:80%;align-self:stretch;align-items:center}.file__name{font-weight:200}.box__content{width:100%;justify-content:center;align-items:center;height:100%;border:1px dashed var(--ez-upload__border--color);border-radius:6px;box-sizing:border-box}.box__container{display:flex;flex-wrap:wrap;background-color:var(--ez-upload__container--background-color);padding:6px;width:100%;border-radius:12px}a:-webkit-any-link{color:#008561;fill:#008561;cursor:pointer;text-decoration:none}progress[value]{display:flex;width:100%;appearance:none;border:1px solid var(--ez-upload__border--color);height:12px;justify-content:flex-start;align-items:center;border-radius:3px;position:relative}progress[value]::-webkit-progress-bar{display:flex;-webkit-appearance:none;width:100%;background-color:rgb(255, 255, 255);border-radius:2px;padding:2px}progress[value]::-webkit-progress-value{display:flex;width:100%;background-color:var(--ez-upload__color--primary)}.text--center{text-align:center}.align--middle{align-self:center;align-items:center}.padding-large{padding:var(--ez-upload--padding--large) 0px}.padding-extra-small{padding:var(--ez-upload--padding--extra-small) 0px}.text{font-family:var(--font-pattern, \"Roboto\");text-shadow:0 0 0 #353535, 0 0 1px transparent}.text--primary{color:var(--ez-upload--text--primary);text-shadow:var(--ez-upload--text-shadow)}.text--secondary{color:var(--ez-upload--text--secondary);text-shadow:var(--ez-upload--text-shadow)}.text--ellipsis{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.text--medium{font-size:14px}.text--small{font-size:12px}.btn-cancel{outline:none;border:none;background-color:unset;cursor:pointer}.btn-cancel::after{content:'';display:flex;background-color:var(--text--primary, #008561);width:8px;height:8px;-webkit-mask-image:var(--ez-upload__btn__cancel-image);mask-image:var(--ez-upload__btn__cancel-image)}.iu_header{display:flex;flex-direction:column;width:100%}.iu__label{padding:var(--space--small);box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--ez-upload--font-family);font-size:var(--text--extra-small);font-weight:var(--ez-upload--font-weight);color:var(--ez-upload--text--primary);text-shadow:var(--ez-upload--text-shadow)}.iu__file-icon{outline:none;border:none;background-color:unset;cursor:pointer}.iu__file-icon:disabled{cursor:unset}.iu__file-icon::after{content:'';display:flex;background-color:var(--text--primary, #626e82);width:9px;height:11px;-webkit-mask-image:var(--ez-upload__file-icon-image);mask-image:var(--ez-upload__file-icon-image)}.iu__file-icon:disabled::after{background-color:var(--text--disable, #AFB6C0)}.iu__icon-label{justify-content:center;display:flex;cursor:pointer;box-sizing:border-box}.background--disabled{background-color:var(--color--disable-secondary, #F2F5F8)}.text--disabled{color:var(--text--disable, #AFB6C0)}.mouse-pointer--disabled{cursor:unset}.appearanceNone{width:0px;height:0px}.row{width:100%;display:flex;flex-wrap:wrap}.col{display:flex;flex-wrap:wrap;align-self:flex-start;box-sizing:border-box}.col--stretch{align-self:stretch}.col--undefined{width:unset}.col--nowrap{flex-wrap:nowrap}@media screen and (min-width: 320px){.col--sd-1{width:8.33333%}.col--sd-2{width:16.66667%}.col--sd-3{width:25%}.col--sd-4{width:33.33333%}.col--sd-5{width:41.66667%}.col--sd-6{width:50%}.col--sd-7{width:58.33333%}.col--sd-8{width:66.66667%}.col--sd-9{width:75%}.col--sd-10{width:83.33333%}.col--sd-11{width:91.66667%}.col--sd-12{width:100%}}@media screen and (min-width: 480px){.col--pn-1{width:8.33333%}.col--pn-2{width:16.66667%}.col--pn-3{width:25%}.col--pn-4{width:33.33333%}.col--pn-5{width:41.66667%}.col--pn-6{width:50%}.col--pn-7{width:58.33333%}.col--pn-8{width:66.66667%}.col--pn-9{width:75%}.col--pn-10{width:83.33333%}.col--pn-11{width:91.66667%}.col--pn-12{width:100%}}@media screen and (min-width: 768px){.col--tb-1{width:8.33333%}.col--tb-2{width:16.66667%}.col--tb-3{width:25%}.col--tb-4{width:33.33333%}.col--tb-5{width:41.66667%}.col--tb-6{width:50%}.col--tb-7{width:58.33333%}.col--tb-8{width:66.66667%}.col--tb-9{width:75%}.col--tb-10{width:83.33333%}.col--tb-11{width:91.66667%}.col--tb-12{width:100%}}@media screen and (min-width: 992px){.col--md-1{width:8.33333%}.col--md-2{width:16.66667%}.col--md-3{width:25%}.col--md-4{width:33.33333%}.col--md-5{width:41.66667%}.col--md-6{width:50%}.col--md-7{width:58.33333%}.col--md-8{width:66.66667%}.col--md-9{width:75%}.col--md-10{width:83.33333%}.col--md-11{width:91.66667%}.col--md-12{width:100%}}@media screen and (min-width: 1200px){.col--ld-1{width:8.33333%}.col--ld-2{width:16.66667%}.col--ld-3{width:25%}.col--ld-4{width:33.33333%}.col--ld-5{width:41.66667%}.col--ld-6{width:50%}.col--ld-7{width:58.33333%}.col--ld-8{width:66.66667%}.col--ld-9{width:75%}.col--ld-10{width:83.33333%}.col--ld-11{width:91.66667%}.col--ld-12{width:100%}}";

const EzUpload = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.ezChange = index.createEvent(this, "ezChange", 7);
    this.ezStartChange = index.createEvent(this, "ezStartChange", 7);
    this.ezCancelWaitingChange = index.createEvent(this, "ezCancelWaitingChange", 7);
    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.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);
        });
        index.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.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) {
      core.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 index$1.initI18n();
  }
  render() {
    return (index.h("div", { ref: (el) => this._dropZone = el, class: this.evalDisabledClass("iu", "background--disabled") }, index.h("div", { class: "iu__container", onClick: () => this.openFilesDialog() }, index.h("div", { class: "iu_header" }, this.label ? index.h("label", { class: this.evalDisabledClass("iu__label", "text--disabled"), title: this.label }, this.label) : null, index.h("div", { class: "padding-large" }, index.h("div", { class: this.evalDisabledClass("iu__icon-label", "mouse-pointer--disabled") }, index.h("button", { class: "iu__file-icon", disabled: !this.enabled }), index.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 &&
      index.h("div", { class: this.evalDisabledClass("padding-extra-small text text--center text--small text--secondary", "text--disabled") }, this.subtitle))), this.buildFooter()), index.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 (index.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 (index.h("div", { class: "iu__item", key: fileName, onClick: evt => evt.stopPropagation() }, index.h("div", { class: "iu__item-label modificador" }, index.h("div", { title: label, class: "col--stretch align--middle file__name text text--primary text--small text--ellipsis align--middle" }, downloadURL ? index.h("a", { href: downloadURL, download: true }, label) : label)), isNaN(progress)
      ?
        null
      :
        index.h("div", { class: "col col--sd-4 col--stretch align--middle" }, index.h("progress", { id: this.buildProgressId(item), value: progress, max: "100" })), this.enabled
      ?
        index.h("div", { class: "col col--stretch align--middle" }, index.h("button", { class: "btn-cancel ", onClick: () => this.removeFile(fileName) }))
      :
        null));
  }
  evalDisabledClass(regularClasses, disabledClass) {
    return this.enabled ? regularClasses : `${regularClasses} ${disabledClass}`;
  }
  get _host() { return index.getElement(this); }
  static get watchers() { return {
    "value": ["observeValue"],
    "requestHeaders": ["observeRequestHeaders"]
  }; }
};
EzUpload.style = ezUploadCss;

exports.ez_upload = EzUpload;
