/*jshint eqnull:true, browser:true */
/*global URI:false, cookie:true */
//
// Twitch geo promise
// Depends on twitch [core, api]


(function (Twitch) {

  var preferredLanguage, receivedLanguage;

  var geoPromise = new RSVP.Promise(function (resolve, reject) {
    Twitch.api.on('ready', function () {
      Twitch.api.get('/api/viewer/info.json')
      .done(function (data) {
        Twitch.preferredLanguage = data.preferred_language;
        Twitch.receivedLanguage = data.received_language;

        var langCookie = cookie.get('language');
        if (langCookie === undefined) {
          Twitch.language.setCookieAndReload(Twitch.receivedLanguage);
        } else if (data.login && langCookie !== data.user_language) {
          Twitch.language.setByAsyncPut(langCookie);
        }
        if (data.eu) {
          window.euCookieNotification();
        }

        Twitch.tracking.spadeAndMixpanel.trackEvent('prime_web_geo_data', {
          platform: 'web',
          geo: data.geo,
          ip: data.ip
        });

        resolve(data);
      })
      .fail(function (jqXHR) {
        reject({status: jqXHR.status});
      });
    });
  });

  Twitch.mixin({
    geo: geoPromise,
    receivedLanguage: receivedLanguage,
    preferredLanguage: preferredLanguage
  });

})(window.Twitch);
