export default class UploadAdapter {
  constructor(props) {
    // The file loader instance to use during the upload.
    this.loader = props.loader;
    this.onFileSelected = props.onFileSelected;
    this.cancel = props.cancel;
  }

  progressFunc = data => {
    this.loader.uploadTotal = data.total;
    this.loader.uploaded = data.loaded;
  };

  // Starts the upload process. (must return a Promise)
  // see https://ckeditor.com/docs/ckeditor5/latest/framework/guides/deep-dive/upload-adapter.html
  upload() {
    return this.loader.file.then(
      file =>
        new Promise((resolve, reject) => {
          this.onFileSelected(
            file,
            response => {
              if (response.error) {
                reject(response.message);
                console.log('error upload', response);
              } else {
                // could be formated in a function given to the constructor
                resolve({
                  // other sizes can be provided
                  default: response.url || response.large,
                });
              }
            },
            this.progressFunc,
          );
        }),
    );
  }

  // Aborts the upload process.
  abort() {
    if (this.cancel) this.cancel();
  }
}
