/* globals Twitch */

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

export default Service.extend({
  isLoading: false,
  userData: null,
  session: injectService(),
  api: injectService(),

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

    // initialize with cached data
    if (Twitch.user.isLoggedIn()) {
      this.set('userData', {
        login: Twitch.user.login(),
        name: Twitch.user.displayName()
      });
    }

    // use the userdata api to get fresh info
    this._loadUserData().catch((error) => {
      if (error && error.status === 401) {
        // This is a known error meaning the user is not logged in.
        return;
      }
      throw error;
    });
  },

  isLoggedIn: computed.bool('userData.login'),
  isAdmin: computed.or('userData.is_admin', 'userData.is_staff'),

  _fetchUserDataPromise: null,
  fetchUserData(reload) {
    if (reload) {
      return this._loadUserData();
    }
    return this._fetchUserDataPromise;
  },

  _loadUserData() {
    this.set('isLoading', true);

    let promise = this.get('session').getCurrentUser().then(userData => {
      if (this.isDestroyed) { return; }
      this.set('userData', userData);
      return userData;
    }).finally(() => {
      if (this.isDestroyed) { return; }
      this.set('isLoading', false);
    });

    this._fetchUserDataPromise = promise;
    return promise;
  }

});
