/* global Twitch */
import Service from 'ember-service';
import { wrap } from 'web-client/utilities/promises';
import { PRIME_GEOS } from 'web-client/utilities/twitch-prime/regions';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import RSVP from 'rsvp';

export default Service.extend({
  session: injectService(),
  tracking: injectService(),
  primeGeos: PRIME_GEOS,
  isPrimeGeo: null,

  isLoggedIn: computed.readOnly('session.isAuthenticated'),
  hasPrime: computed.readOnly('session.userData.has_premium'),

  init() {
    this._super(...arguments);

    return this.getGeo().then(data => {
      if(this.isDestroyed) { return; }

      return this.set('isPrimeGeo', this.isGeoPrimeRegion(data.geo));
    });
  },

  showPrimeContent: computed('isPrimeGeo', 'hasPrime', 'isLoggedIn', function() {
    return this.get('isPrimeGeo') || (this.get('hasPrime') && this.get('isLoggedIn'));
  }),

  getGeo() {
    return wrap(() => Twitch.geo, 'GeoService#getGeo');
  },

  isGeoPrimeRegion(geo) {
    return this.get('primeGeos').includes(geo);
  },

  getPrimeGeoPromise() {
    return new RSVP.Promise((resolve, reject) => {
      return this.getGeo().then(data => {
        return resolve(this.isGeoPrimeRegion(data.geo));
      }).catch(error => {
        reject(error);
      });
    }, 'PremiumGeo#getPrimeGeoPromise');
  }
});
