"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getUploadUrl = getUploadUrl;
exports.sendFileToS3 = void 0;

var _constants = require("@instructure/quiz-common/lib/constants");

var _contentDisposition = _interopRequireDefault(require("content-disposition"));

var _Fetcher = _interopRequireDefault(require("../util/Fetcher"));

function getUploadUrl(url) {
  var urlFetcher = new _Fetcher.default({
    callType: _constants.FILE_UPLOAD_URL_CALL
  });
  return urlFetcher.get(url);
} // This fxn requires a secondary fxn as an argument.
// It gets the url to post the file to S3 from the request and returns a promise.


var sendFileToS3 = function sendFileToS3(file, onSuccess, onError, altText) {
  var fileFetcher = new _Fetcher.default({
    asyncResponseHandler: function asyncResponseHandler() {},
    callType: _constants.FILE_UPLOAD_CALL,
    headers: {
      'Content-Type': file.type,
      // This thing handles unicode filenames appropriately for HTTP headers - yay
      'Content-Disposition': (0, _contentDisposition.default)(file.name)
    },
    onError: onError
  });
  return function (res) {
    // After uploading, the signed portion of the URL is useless and incorrect
    var s3url = res.url.split(/[?#]/)[0];
    return fileFetcher.put("".concat(res.url), {
      body: file
    }).then(function (ref) {
      onSuccess(s3url, altText);
    });
  };
};

exports.sendFileToS3 = sendFileToS3;