import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { useCallback, useContext } from 'react';
import ReactDOM from 'react-dom';
import { FileUploaderFileStatus } from "../../fileUtils";
import { FileUploaderControlContext } from "../../FileUploaderControlContext";
export var useUpload = function useUpload(request, onRequestSuccess, onRequestError) {
  var _useContext = useContext(FileUploaderControlContext),
    setFileStatus = _useContext.setFileStatus;
  var switchToLoading = useCallback(function (fileId) {
    setFileStatus(fileId, FileUploaderFileStatus.Loading);
  }, [setFileStatus]);
  var switchToSuccess = useCallback(function (fileId) {
    setFileStatus(fileId, FileUploaderFileStatus.Uploaded);
    onRequestSuccess == null || onRequestSuccess(fileId);
  }, [setFileStatus, onRequestSuccess]);
  var switchToError = useCallback(function (fileId) {
    setFileStatus(fileId, FileUploaderFileStatus.Error);
    onRequestError == null || onRequestError(fileId);
  }, [setFileStatus, onRequestError]);
  return useCallback( /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(file) {
      var id;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            id = file.id;
            ReactDOM.flushSync(function () {
              switchToLoading(id);
            });
            _context.prev = 2;
            _context.next = 5;
            return request == null ? void 0 : request(file);
          case 5:
            switchToSuccess(id);
            _context.next = 11;
            break;
          case 8:
            _context.prev = 8;
            _context.t0 = _context["catch"](2);
            switchToError(id);
          case 11:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[2, 8]]);
    }));
    return function (_x) {
      return _ref.apply(this, arguments);
    };
  }(), [request, switchToSuccess, switchToLoading, switchToError]);
};