import {BlobRecord} from "activestorage/src/blob_record";
import {FileChecksum} from "activestorage/src/file_checksum";
import $ from 'jquery';

const uploadFile = (file, uploader, input, callback, blobRecordClass, fileChecksumClass) => {
  const BlobRecordClass = blobRecordClass || BlobRecord
  const FileChecksumClass = fileChecksumClass || FileChecksum

  uploader.then((evaporate) => {
    var url = input.data("directUploadUrl");

    FileChecksumClass.create(file, function (error, checksum) {
      var blob = new BlobRecordClass(file, checksum, url)
      blob.create(function (error) {
        const hiddenField = input
          .attr("type", "hidden")
          .attr("value", blob.attributes.signed_id)
          .attr(name, input.name);
        $("form").append(hiddenField);

        evaporate.add({
          file: file,
          name: blob.attributes.key,
          progress: (percent, stats) => {
            if (App.FileUploadProgress._findProgressBar(blob.attributes.key)) {
              App.FileUploadProgress.updateProgressBar(blob.attributes.key, percent * 100);
            }
          },
          complete: (xhr, awsObjectKey) => {
            App.FileUploadProgress.removeProgressBar(blob.attributes.key)
            callback();
          },
          error: (mssg) => {
            App.FileUploadProgress.showError(blob.attributes.key, error);
          },
          paused: () => {},
          pausing: () => {},
          resumed: () => {},
          cancelled: () => {},
          started: (fileKey) => {
            const progressBar = App.FileUploadProgress.createProgressBar(blob.attributes.key);
            input.parents("form").after(progressBar);
            App.FileUploadProgress.showProgressBar(blob.attributes.key);
          },
          uploadInitiated: (s3Id) => {},
          warn: (mssg) => {}
        })
      });
    });
  });
}

export default uploadFile;

window.uploadFile = uploadFile;
