"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ToolbarDownloadButton = exports.ErrorViewDownloadButton = exports.DisabledToolbarDownloadButton = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _analyticsNext = require("@atlaskit/analytics-next");
var _download = _interopRequireDefault(require("@atlaskit/icon/core/migration/download"));
var _mediaClient = require("@atlaskit/media-client");
var _mediaUi = require("@atlaskit/media-ui");
var _react = _interopRequireWildcard(require("react"));
var _reactIntlNext = require("react-intl-next");
var _downloadButtonClicked = require("./analytics/events/ui/downloadButtonClicked");
var _download2 = require("./analytics/events/operational/download");
var _analytics = require("./analytics");
var _failedPreviewDownloadButtonClicked = require("./analytics/events/ui/failedPreviewDownloadButtonClicked");
var _styleWrappers = require("./styleWrappers");
var _errors = require("./errors");
var _tooltip = _interopRequireDefault(require("@atlaskit/tooltip"));
var _abuseModal = require("@atlaskit/media-ui/abuseModal");
var _excluded = ["analyticspayload", "onClick", "tooltip"];
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 downloadIcon = /*#__PURE__*/_react.default.createElement(_download.default, {
  color: "currentColor",
  spacing: "spacious",
  label: "Download"
});
function noop() {}
function DownloadButton(_ref) {
  var analyticspayload = _ref.analyticspayload,
    _ref$onClick = _ref.onClick,
    providedOnClick = _ref$onClick === void 0 ? noop : _ref$onClick,
    tooltip = _ref.tooltip,
    rest = (0, _objectWithoutProperties2.default)(_ref, _excluded);
  var _useAnalyticsEvents = (0, _analyticsNext.useAnalyticsEvents)(),
    createAnalyticsEvent = _useAnalyticsEvents.createAnalyticsEvent;
  var onClick = (0, _react.useCallback)(function (event, analyticsEvent) {
    (0, _analytics.fireAnalytics)(analyticspayload, createAnalyticsEvent);
    providedOnClick(event, analyticsEvent);
  }, [analyticspayload, providedOnClick, createAnalyticsEvent]);
  var downloadButton = /*#__PURE__*/_react.default.createElement(_mediaUi.MediaButton, (0, _extends2.default)({}, rest, {
    onClick: onClick
  }));
  return tooltip ? /*#__PURE__*/_react.default.createElement(_tooltip.default, {
    content: tooltip,
    position: "bottom",
    tag: "span"
  }, downloadButton) : downloadButton;
}
var createItemDownloader = function createItemDownloader(file, mediaClient, options) {
  return /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
    var collectionName, traceContext, createAnalyticsEvent, id, name;
    return _regenerator.default.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          collectionName = options.collectionName, traceContext = options.traceContext, createAnalyticsEvent = options.createAnalyticsEvent;
          id = file.id;
          name = !(0, _mediaClient.isErrorFileState)(file) ? file.name : undefined;
          mediaClient.file.downloadBinary(id, name, collectionName, traceContext).then(function () {
            (0, _analytics.fireAnalytics)((0, _download2.createDownloadSucceededEventPayload)(file, traceContext), createAnalyticsEvent);
          }).catch(function (e) {
            (0, _analytics.fireAnalytics)((0, _download2.createDownloadFailedEventPayload)(file.id, new _errors.MediaViewerError('download', e), file, traceContext), createAnalyticsEvent);
          });
        case 4:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
};
var useDownloadButtonDisabledProps = function useDownloadButtonDisabledProps(mediaClient) {
  var _useIntl = (0, _reactIntlNext.useIntl)(),
    formatMessage = _useIntl.formatMessage;
  var isDisabled = mediaClient.config.enforceDataSecurityPolicy;
  var tooltip = isDisabled ? formatMessage(_mediaUi.messages.download_disabled_security_policy) : undefined;
  return {
    isDisabled: isDisabled,
    tooltip: tooltip
  };
};
var DownloadItem = function DownloadItem(_ref3) {
  var testId = _ref3.testId,
    fileState = _ref3.fileState,
    mediaClient = _ref3.mediaClient,
    collectionName = _ref3.collectionName,
    appearance = _ref3.appearance,
    analyticspayload = _ref3.analyticspayload,
    traceContext = _ref3.traceContext,
    iconBefore = _ref3.iconBefore,
    children = _ref3.children;
  var _useState = (0, _react.useState)(false),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    isAbuseModalOpen = _useState2[0],
    setIsAbuseModalOpen = _useState2[1];
  var _useAnalyticsEvents2 = (0, _analyticsNext.useAnalyticsEvents)(),
    createAnalyticsEvent = _useAnalyticsEvents2.createAnalyticsEvent;
  var _useDownloadButtonDis = useDownloadButtonDisabledProps(mediaClient),
    isDisabled = _useDownloadButtonDis.isDisabled,
    tooltip = _useDownloadButtonDis.tooltip;
  var shouldRenderAbuseModal = !(0, _mediaClient.isErrorFileState)(fileState) && !!fileState.abuseClassification;
  var itemDownloader = createItemDownloader(fileState, mediaClient, {
    collectionName: collectionName,
    createAnalyticsEvent: createAnalyticsEvent,
    traceContext: traceContext
  });
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, shouldRenderAbuseModal && /*#__PURE__*/_react.default.createElement(_abuseModal.AbuseModal, {
    isOpen: isAbuseModalOpen,
    onConfirm: itemDownloader,
    onClose: function onClose() {
      return setIsAbuseModalOpen(false);
    }
  }), /*#__PURE__*/_react.default.createElement(DownloadButton, {
    testId: testId,
    appearance: appearance,
    analyticspayload: analyticspayload,
    isDisabled: isDisabled,
    tooltip: tooltip,
    onClick: function onClick() {
      if (shouldRenderAbuseModal) {
        setIsAbuseModalOpen(true);
      } else {
        itemDownloader();
      }
    },
    iconBefore: iconBefore
  }, children));
};
var ErrorViewDownloadButton = exports.ErrorViewDownloadButton = function ErrorViewDownloadButton(_ref4) {
  var fileState = _ref4.fileState,
    mediaClient = _ref4.mediaClient,
    error = _ref4.error,
    traceContext = _ref4.traceContext,
    collectionName = _ref4.collectionName;
  var downloadEvent = (0, _failedPreviewDownloadButtonClicked.createFailedPreviewDownloadButtonClickedEvent)(fileState, error);
  var testId = 'media-viewer-error-download-button';
  return /*#__PURE__*/_react.default.createElement(_styleWrappers.DownloadButtonWrapper, null, /*#__PURE__*/_react.default.createElement(DownloadItem, {
    testId: testId,
    analyticspayload: downloadEvent,
    appearance: "primary",
    fileState: fileState,
    mediaClient: mediaClient,
    collectionName: collectionName,
    traceContext: traceContext
  }, /*#__PURE__*/_react.default.createElement(_reactIntlNext.FormattedMessage, _mediaUi.messages.download)));
};
var ToolbarDownloadButton = exports.ToolbarDownloadButton = function ToolbarDownloadButton(_ref5) {
  var state = _ref5.state,
    mediaClient = _ref5.mediaClient,
    identifier = _ref5.identifier,
    traceContext = _ref5.traceContext;
  // TODO [MS-1731]: make it work for external files as well
  if ((0, _mediaClient.isExternalImageIdentifier)(identifier)) {
    return null;
  }
  var downloadEvent = (0, _downloadButtonClicked.createDownloadButtonClickedEvent)(state);
  var testId = 'media-viewer-download-button';
  return /*#__PURE__*/_react.default.createElement(DownloadItem, {
    testId: testId,
    analyticspayload: downloadEvent,
    fileState: state,
    mediaClient: mediaClient,
    collectionName: identifier.collectionName,
    traceContext: traceContext,
    iconBefore: downloadIcon
  });
};
var DisabledToolbarDownloadButton = exports.DisabledToolbarDownloadButton = /*#__PURE__*/_react.default.createElement(_mediaUi.MediaButton, {
  isDisabled: true,
  iconBefore: downloadIcon
});