"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CustomViewer = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _errors = require("../../errors");
var _react = _interopRequireWildcard(require("react"));
var _loading = require("../../loading");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
var CustomViewer = exports.CustomViewer = function CustomViewer(_ref) {
  var mediaClient = _ref.mediaClient,
    item = _ref.item,
    customRendererConfig = _ref.customRendererConfig,
    collectionName = _ref.collectionName,
    onSuccess = _ref.onSuccess,
    onError = _ref.onError;
  var _useState = (0, _react.useState)(),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    getBinaryContent = _useState2[0],
    setGetBinaryContent = _useState2[1];
  (0, _react.useEffect)(function () {
    setGetBinaryContent(undefined);
    var abortController = new AbortController();
    // This sets the 'getBinaryContent' to an async function that fetches the binary content of the file
    // The 'getBinaryContent' function has to be updated when the item changes
    // This approach handles aborting in-progress request outside of the custom-renderer concern
    if (item.status === 'processed' || item.status === 'failed-processing') {
      setGetBinaryContent(function () {
        return function () {
          return mediaClient.mediaStore.getFileBinary(item.id, collectionName, abortController);
        };
      });
    }
    return function () {
      return abortController.abort();
    };
  }, [collectionName, item, mediaClient]);
  var onLoadFailed = (0, _react.useCallback)(function (error) {
    var mediaError = new _errors.MediaViewerError('custom-viewer-error', error);
    onError(mediaError, item);
  }, [item, onError]);
  if (!getBinaryContent) {
    return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
  }
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, customRendererConfig.renderContent({
    fileItem: item,
    getBinaryContent: getBinaryContent,
    onLoad: onSuccess,
    onError: onLoadFailed
  }));
};