import ENV from '../config/environment';
import Evented from 'ember-evented';
import injectService from 'ember-service/inject';
import PubsubDriver from 'pubsub-js-client/PubsubDriver';
import Service from 'ember-service';

export default Service.extend(Evented, {
  globals: injectService(),
  client: null,

  init() {
    this._super(...arguments);
    if (!this.get('client')) {
      this.set('client', PubsubDriver.getInstance(ENV.pubsub.environment));
    }
  },

  on(event) {
    if (!this.has(event)) {
      this._pubsubListen(event);
    }
    this._super(...arguments);
  },

  off(event) {
    this._super(...arguments);
    // remove pubsub listener if nothing else is watching the event
    if (!this.has(event)) {
      this._pubsubUnlisten(event);
    }
  },

  parsePayload(payload) {
    try {
      return JSON.parse(payload);
    } catch(e) {
      console.error('Client failed to parse payload', payload);
    }
    return null;
  },

  _pubsubListen(topic) {
    this.get('client').Listen({
      topic,
      message: (payload) => {
        this.trigger(topic, this.parsePayload(payload));
      }
    });
  },

  _pubsubUnlisten(topic) {
    this.get('client').Unlisten({ topic });
  }
});
