/* @flow */
import { CameraRoll, Platform } from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';

import type { Auth } from './apiTypes';
import { getAuthHeader, getFullUrl } from '../utils/url';
import userAgent from '../utils/userAgent';

export default (src: string, auth: Auth) => {
  const fullUrlWithAPIKey = `${getFullUrl(src, auth.realm)}?api_key=${auth.apiKey}`;

  if (Platform.OS === 'ios') {
    return CameraRoll.saveToCameraRoll(fullUrlWithAPIKey);
  }
  return RNFetchBlob.config({
    addAndroidDownloads: {
      path: `${RNFetchBlob.fs.dirs.DownloadDir}/${src.split('/').pop()}`,
      useDownloadManager: true,
      mime: 'text/plain', // Android DownloadManager fails if the url is missing a file extension
      title: src.split('/').pop(),
      notification: true,
    },
  }).fetch('GET', getFullUrl(src, auth.realm), {
    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
    'User-Agent': userAgent,
    Authorization: getAuthHeader(auth.email, auth.apiKey),
  });
};

/* @flow */
import { CameraRoll, Platform } from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';

import type { Auth } from './apiTypes';
import { getAuthHeader, getFullUrl } from '../utils/url';
import userAgent from '../utils/userAgent';

export default (src: string, auth: Auth) => {
  const absoluteUrl = getFullUrl(src, auth.realm);

  if (Platform.OS === 'ios') {
    const delimiter = absoluteUrl.includes('?') ? '&' : '?';
    const urlWithApiKey = `${absoluteUrl}${delimiter}api_key=${auth.apiKey}`;
    return CameraRoll.saveToCameraRoll(urlWithApiKey);
  }
  return RNFetchBlob.config({
    addAndroidDownloads: {
      path: `${RNFetchBlob.fs.dirs.DownloadDir}/${src.split('/').pop()}`,
      useDownloadManager: true,
      mime: 'text/plain', // Android DownloadManager fails if the url is missing a file extension
      title: src.split('/').pop(),
      notification: true,
    },
  }).fetch('GET', absoluteUrl, {
    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
    'User-Agent': userAgent,
    Authorization: getAuthHeader(auth.email, auth.apiKey),
  });
};

Tweak URL-with-key logic to be a bit more defensive.
download: Tweak URL-with-key logic to be a bit more defensive.

It's not entirely obvious whether it's possible for the `src` URL to
already have a query part, in which case we should be using `&` rather
than `?` as the delimiter.  Rather than make and justify an assumption
that that can't happen, borrow the logic we have for handling this in
`appendAuthToImages` in js.js.

There isn't currently an easy way to share the actual code between
these places (one inside the webview, one in the main RN environment),
so that means copying.  Fortunately this is a tiny amount of code and
its logic isn't likely to need to change, so that isn't so bad.
