import Service from 'ember-service';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';

const PROMISES = {};

export default Service.extend({
  api: injectService(),
  globals: injectService(),
  session: injectService(),
  userId: null,

  isFlEnabled: computed.or('globals.isFlEnabled', 'isFlWhitelisted'),
  flWhitelist: computed.readOnly('globals.flEnabledList'),

  isFlWhitelisted: computed('flWhitelist', function() {
    let whitelist = [];

    if (this.get('flWhitelist') !== null && this.get('flWhitelist') !== undefined) {
      whitelist = this.get('flWhitelist').split(',').map(Number);
    }

    return whitelist.includes(this.get('session.userData.id'));
  }),

  getGameSettings(rawGameName) {
    let gameName = encodeURIComponent(rawGameName);
    if(PROMISES[gameName]) {
      return PROMISES[gameName];
    }
    let params = {
      cache: Date.now() // IE11 caches AJAX requests so we need to bust the cache
    };

    let resp = this.get('api').request('get', `games/${gameName}/settings`, params)
      .then(response => response.details_enabled)
      .finally(() => { delete PROMISES[gameName];});
    PROMISES[gameName] = resp;
    return resp;
  },

  getUserInfo(broadcasterName) {
    return this.get('api').request('get', `/kraken/users/${broadcasterName}`);
  }
});
