import Ember from 'ember';
import { libs } from 'web-client/utilities/presence-util';
import injectService from 'ember-service/inject';
import Service from 'ember-service';
import Evented from 'ember-evented';
import run from 'ember-runloop';

const { Logger } = Ember;

export default Service.extend(Evented, {
  session: injectService(),
  store: injectService(),

  _parsePresence(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);
    }
  },

  _convertSettingsToJsonApi(payload) {
    return {
      data: {
        id: this.get('session.userData.id'),
        type: 'presence-settings',
        attributes: payload.data
      }
    };
  },

  _pushPresence(payload) {
    let structuredPayload = this._convertSettingsToJsonApi(payload);
    this.get('store').push(structuredPayload);
  },

  listen() {
    let { userData } = this.get('session');
    let userId = userData ? userData.id : undefined;
    let auth = userData ? userData.token : undefined;

    libs.pubsub.Listen({
      auth,
      topic: `presence.${userId}`,
      message: (data) => {
        run(() => {
          let payload = this._parsePresence(data);
          if (payload.type === 'settings') {
            this._pushPresence(payload);
          }
        });
      }
    });
  }
});
