/* globals Twitch */

/**
  This file handles API requests that POST data with MIME type "multipart/form-data" (usually images and file uploads).
**/

import request from 'ember-ajax/request';
import xhrPromise from 'web-client/utilities/xhr-promise';

export default function uploadThumbnail({ videoId, file, data }) {
  let url = thumbnailUrl(videoId);

  data.image = file;
  return uploadData({ url, data });
}

/**
  This function handles calls to old web/web routes, such as /settings, which require specific configurations.
  TODO:  Unify this with exisitng xhr-based function "uploadData" below
**/
export function uploadLegacyData(url, data) {
  let formData = new FormData();

  Object.keys(data).forEach((key) => {
    formData.append(key, data[key]);
  });

  return request(url, {
    type: 'POST',
    contentType: false,
    processData: false,
    dataType: 'html',
    data: formData,
    beforeSend(xhr) {
      xhr.setRequestHeader('Twitch-Api-Token', Twitch.storage.legacy.get('api_token'));
    }
  });
}

export function uploadData({ url, data = {} }) {
  // Use XHR from iframe to avoid pre-flight requests which the endpoint
  // cannot handle.
  let xhr = Twitch.api._createXHR();
  let formData = new FormData();

  Object.keys(data).forEach((key) => {
    formData.append(key, data[key]);
  });

  xhr.open('POST', url, true);
  xhr.setRequestHeader('Twitch-Api-Token', Twitch.storage.legacy.get('api_token'));
  xhr.setRequestHeader('Client-ID', Twitch.api.config.clientID);

  let promise = xhrPromise(xhr);

  xhr.send(formData);

  return promise;
}

function thumbnailUrl(videoId) {
  return `${Twitch.api.config.baseUrl}/api/vods/${videoId}/upload_thumbnail`;
}
