import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { extractSmartLinkDownloadUrl } from '@atlaskit/link-extractors';
import { CardAction } from '../../constants';
import { ActionName } from '../../index';
import { getDefinitionId, getExtensionKey, getResourceType } from '../../state/helpers';
import { downloadUrl as download } from '../../utils';
import { canShowAction } from '../../utils/actions/can-show-action';
import { getActionsFromJsonLd } from '../common/actions/extractActions';
export var extractInvokeDownloadAction = function extractInvokeDownloadAction(_ref) {
  var actionOptions = _ref.actionOptions,
    appearance = _ref.appearance,
    id = _ref.id,
    response = _ref.response;
  if (!canShowAction(CardAction.DownloadAction, actionOptions)) {
    return;
  }
  var data = response.data;
  var downloadActionExists = getActionsFromJsonLd(data).find(function (action) {
    return action['@type'] === 'DownloadAction';
  });
  if (downloadActionExists) {
    var downloadUrl = extractSmartLinkDownloadUrl(response);
    return {
      actionFn: function () {
        var _actionFn = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
          return _regeneratorRuntime.wrap(function (_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                return _context.abrupt("return", download(downloadUrl));
              case 1:
              case "end":
                return _context.stop();
            }
          }, _callee);
        }));
        function actionFn() {
          return _actionFn.apply(this, arguments);
        }
        return actionFn;
      }(),
      actionSubjectId: 'downloadDocument',
      actionType: ActionName.DownloadAction,
      definitionId: getDefinitionId(response),
      display: appearance,
      extensionKey: getExtensionKey(response),
      id: id,
      resourceType: getResourceType(response)
    };
  }
};