/* global Twitch, $ */

import { wrap } from 'web-client/utilities/promises';
import injectService from 'ember-service/inject';
import Service from 'ember-service';
import { guidFor } from 'ember-metal/utils';

const DEFAULT_API_VERSION = 4;

export default Service.extend({
  session: injectService(),

  requestUrl(url) {
    return Twitch.api.config.baseUrl + url;
  },

  request(method, url, data, options = {}) {
    // Hide quirky, IE8-compatible verb name
    if (method === 'delete') {
      method = 'del';
    }

    options.version = options.version || DEFAULT_API_VERSION;

    // JQuery fires ajaxSend and ajaxComplete for JSON AJAX requests, but not JSONP,
    // which is what Twitch.api uses. the Ember Test framework uses the events to make
    // tests wait for all ajax requests to complete. Therefore we need to manually
    // trigger the events here with a unique ID to make the tests track them.
    let xhrId = guidFor(`${method}:${url}`);
    $('body').trigger('ajaxSend', xhrId);

    return wrap(() => Twitch.api[method](url, data, options), 'TwitchApiService#request')
    .finally(() => {
      $('body').trigger('ajaxComplete', xhrId);
    });
  },

  /*
   * For sending OAuth Token Authorized Requests instead of traditional Cookie Auth
   *
   * Same signature as request() but will automatically inject the users OAuth
   * Token if available.
   */
  authRequest(method, url, data, options) {
    return this.get('session').getOAuthToken().then(token => {
      options = options || {};
      if (token !== "") {
        if (!options.headers) {
          options.headers = {};
        }
        if (!options.headers.Authorization) {
          options.headers.Authorization = `OAuth ${token}`;
        }
      }
      return this.request(method, url, data, options);
    });
  }
});
