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 const extractInvokeDownloadAction = ({
  actionOptions,
  appearance,
  id,
  response
}) => {
  if (!canShowAction(CardAction.DownloadAction, actionOptions)) {
    return;
  }
  const data = response.data;
  const downloadActionExists = getActionsFromJsonLd(data).find(action => action['@type'] === 'DownloadAction');
  if (downloadActionExists) {
    const downloadUrl = extractSmartLinkDownloadUrl(response);
    return {
      actionFn: async () => download(downloadUrl),
      actionSubjectId: 'downloadDocument',
      actionType: ActionName.DownloadAction,
      definitionId: getDefinitionId(response),
      display: appearance,
      extensionKey: getExtensionKey(response),
      id,
      resourceType: getResourceType(response)
    };
  }
};