import { DirectUpload } from '@rails/activestorage';
import ProgressBar from './progress-bar';

/**
  Uploader class is a delegate for DirectUpload instance
  used to track lifecycle and progress of an upload.
  */
export default class Uploader {
  constructor(input, file, directUploadUrl) {
    this.directUpload = new DirectUpload(file, directUploadUrl, this);
    this.progressBar = new ProgressBar(input, this.directUpload.id, file);
  }

  start() {
    this.progressBar.start();

    return new Promise((resolve, reject) => {
      this.directUpload.create((error, attributes) => {
        if (error) {
          this.progressBar.error(error);
          reject(error);
        } else {
          resolve(attributes.signed_id);
        }
        this.progressBar.end();
        this.progressBar.destroy();
      });
    });
  }

  uploadRequestDidProgress(event) {
    const progress = (event.loaded / event.total) * 100;
    if (progress) {
      this.progressBar.progress(progress);
    }
  }

  directUploadWillStoreFileWithXHR(xhr) {
    xhr.upload.addEventListener('progress', event =>
      this.uploadRequestDidProgress(event)
    );
  }
}

@@ -563,16 +563,19 @@
 e((error
+Msg
 , attrib
@@ -602,16 +602,19 @@
 f (error
+Msg
 ) %7B%0A    
@@ -643,24 +643,27 @@
 .error(error
+Msg
 );%0A         
@@ -670,21 +670,35 @@
  reject(
-error
+new Error(errorMsg)
 );%0A     

make DirectUpload errors return true error objects