import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';

const { merge } = Ember;

export const WEB_CLIENT_CLIENT_ID = 'jzkbprff40iqj646a697cyrvl0zt2m6';
export const CLIENT_ID_HEADER = 'Client-ID';

const JSONP_OPTIONS = {
  global: false,
  dataType: 'jsonp',
  data: {}
};

const CORS_OPTIONS = {
  global: false,
  dataType: 'json',
  headers: {},
  xhrFields: {}
};

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

  isCrossOriginEnabled: computed(function() {
    return 'XMLHttpRequest' in window &&
           'withCredentials' in new XMLHttpRequest();
  }),

  // ember-ajax only uses headers if host matches trustedHosts,
  // and we want to add auth headers for all twitch hosts.
  trustedHosts: [ /\.twitch.tv/ ],
  headers: computed(function() {
    let headers = {};

    if (this.get('isCrossOriginEnabled')) {
      let auth = `OAuth ${this.get('session.userData.chat_oauth_token')}`;
      headers.Authorization = auth;
    }

    return headers;
  }),

  _optionsForJSONP(_options) {
    let token = this.get('session.userData.chat_oauth_token');
    let options = {};

    merge(options, JSONP_OPTIONS);
    merge(options, _options);

    options.data.client_id = options.data.client_id || WEB_CLIENT_CLIENT_ID;
    options.data.oauth_token = options.data.oauth_token || token;
    return options;
  },

  _optionsForCORS(_options) {
    let options = {};

    merge(options, CORS_OPTIONS);
    merge(options, _options);

    options.headers[CLIENT_ID_HEADER] = options.headers[CLIENT_ID_HEADER] || WEB_CLIENT_CLIENT_ID;
    options.xhrFields.withCredentials = options.xhrFields.withCredentials || false;
    return options;
  },

  request(url, options={}) {
    if (this.get('isCrossOriginEnabled')) {
      options = this._optionsForCORS(options);
    } else {
      options = this._optionsForJSONP(options);
    }

    return this._super(url, options);
  }
});
