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

export default Service.extend({

  init() {
    this._super();
    this._session = null;
  },

  globals: injectService(),
  apiHostport: computed.alias('globals.apiHostport'),
  session: injectService(),
  tracking: injectService(),

  tmijs: computed(function () {
    return window.TMI;
  }),

  tmiSession: computed('tmijs', 'session', 'apiHostport', function () {
    let session = this.get('session');
    let apiHostport = this.get('apiHostport');
    let tmijs = this.get('tmijs');

    return session.getCurrentUser().catch(e => {
      if (e.status === 401) {
        /* If the user is unauthenticated, pass a blank object as their
         * userData */
        return {};
      }
      throw e;
    }).then(userData => {
      if (this.isDestroyed) { return; }

      let cfg = {
        userId: userData.id,
        username: userData.login,
        oauthToken: userData.chat_oauth_token,
        apiHostport
      };

      this._session = tmijs.createSession(cfg);
      this._session.on('connection:disconnected', (trackingData) => {
        this.get('tracking').trackEvent({
          event: 'chat_forced_disconnect',
          data: trackingData
        });
      });

      return this._session;
    });
  }),

  chatOauthToken: computed(function () {
    let session = this.get('session');
    return session.getCurrentUser().then(userData => userData.chat_oauth_token);
  }),

  sendWhisper(username, message) {
    return this.get('tmiSession').then(session => {
      if (this.isDestroyed) {
        return;
      }
      return session.sendWhisper(username, message);
    });
  },

  ignoreUser(username, reason, options={}) {
    options.isWhisper = options.isWhisper || false;
    return this.get('tmiSession').then(session => {
      if (this.isDestroyed) {
        return;
      }
      return session.ignoreUser(username, reason, options.isWhisper);
    });
  },

  unignoreUser(username) {
    return this.get('tmiSession').then(session => {
      if (this.isDestroyed) {
        return;
      }
      return session.unignoreUser(username);
    });
  },

  isIgnored(username) {
    return this.get('tmiSession').then(session => {
      if (this.isDestroyed) {
        return;
      }
      return session.isIgnored(username);
    });
  },

  willDestroy() {
    if (this._session) {
      this._session.destroy();
    }
    this._super();
  }
});
