"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.extractInvokeDownloadAction = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _linkExtractors = require("@atlaskit/link-extractors");
var _constants = require("../../constants");
var _index = require("../../index");
var _helpers = require("../../state/helpers");
var _utils = require("../../utils");
var _canShowAction = require("../../utils/actions/can-show-action");
var _extractActions = require("../common/actions/extractActions");
var extractInvokeDownloadAction = exports.extractInvokeDownloadAction = function extractInvokeDownloadAction(_ref) {
  var actionOptions = _ref.actionOptions,
    appearance = _ref.appearance,
    id = _ref.id,
    response = _ref.response;
  if (!(0, _canShowAction.canShowAction)(_constants.CardAction.DownloadAction, actionOptions)) {
    return;
  }
  var data = response.data;
  var downloadActionExists = (0, _extractActions.getActionsFromJsonLd)(data).find(function (action) {
    return action['@type'] === 'DownloadAction';
  });
  if (downloadActionExists) {
    var downloadUrl = (0, _linkExtractors.extractSmartLinkDownloadUrl)(response);
    return {
      actionFn: function () {
        var _actionFn = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
          return _regenerator.default.wrap(function (_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                return _context.abrupt("return", (0, _utils.downloadUrl)(downloadUrl));
              case 1:
              case "end":
                return _context.stop();
            }
          }, _callee);
        }));
        function actionFn() {
          return _actionFn.apply(this, arguments);
        }
        return actionFn;
      }(),
      actionSubjectId: 'downloadDocument',
      actionType: _index.ActionName.DownloadAction,
      definitionId: (0, _helpers.getDefinitionId)(response),
      display: appearance,
      extensionKey: (0, _helpers.getExtensionKey)(response),
      id: id,
      resourceType: (0, _helpers.getResourceType)(response)
    };
  }
};