import on from 'ember-evented/on';
import Ember from 'ember';
import injectService from 'ember-service/inject';
import { libs } from 'web-client/utilities/friends-list/settings';
import Evented from 'ember-evented';
const { Logger, Service, isEqual } = Ember;

export default Service.extend(Evented, {
  session: injectService(),
  api: injectService('twitch-friends-list/api'),
  requests: injectService('twitch-friends-list/requests'),
  store: injectService(),
  hasSetUpListen: false,

  resyncFriendsList: on('init', function() {
    libs.pubsub.on("connected", () => {
      this.get('api').initializeFriendsList();
      this.get('requests').fetchNewRequests();
    });
  }),

  _parseMessage(payload) {
    try {
      return JSON.parse(payload);
    } catch(e) {
      // I don't think we can do anything productive here without better client side logging.
      Logger.error('Client failed to parse payload', payload);
    }
  },

  pushPresence(payload) {
    let parsedMessage = this._parseMessage(payload);
    this.get('store').pushPayload('friends-list-user', parsedMessage);
  },

  listen() {
    let userId = this.get('session.userData.id');
    let auth = this.get('session.userData.chat_oauth_token');

    if (!this.get('hasSetUpListen')) {
      libs.pubsub.Listen({
        auth,
        topic: `presence.${userId}`,
        message: this.pushPresence.bind(this)
      });

      libs.pubsub.Listen({
        auth,
        topic: `friendship.${userId}`,
        message: (data) => {
          let payload = this._parseMessage(data);
          if (isEqual(payload.change, 'requested')) {
            this.trigger('requestedMessage', payload);
          } else if (isEqual(payload.change, 'accepted')) {
            this.trigger('acceptedMessage', payload);
          }
        }
      });
      this.set('hasSetUpListen', true);
    }
  },

  willDestroy() {
    let userId = this.get('session.userData.id');
    libs.pubsub.Unlisten({
      topic: `presence.${userId}`
    });
    libs.pubsub.Unlisten({
      topic: `friendship.${userId}`
    });
    libs.pubsub.off("connected");
    this._super(...arguments);
  }
});
