export default 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));
    });
  }
}
