/* globals Twitch */
import injectService from 'ember-service/inject';
import { equal } from 'ember-computed';
import Service from 'ember-service';
import on from 'ember-evented/on';
import computed from 'ember-computed';

export default Service.extend({
  api: injectService(),
  polling: injectService('twitch-presence/backend/polling'),
  ping: injectService('twitch-presence/backend/ping'),
  pubsub: injectService('twitch-presence/pubsub'),
  store: injectService(),
  tracking: injectService(),

  settings: null,
  areSettingsLoaded: false,

  isOnline: equal('settings.share', 'full'),
  isInvisible: equal('settings.share', 'none'),

  sessionId: computed(function() {
    let sessionId = Twitch.storage.get('sessionId', {storage: 'sessionStorage'});
    if (!sessionId) {
      sessionId = Twitch.idsForMixpanel.createUniqueId();
      Twitch.storage.set('sessionId', sessionId, {storage: 'sessionStorage'});
    }
    return sessionId;
  }),

  initSettings: on('init', function () {
    this.get('store').queryRecord('presence-settings', {}).then(settings => {
      if (this.isDestroyed || this.isDestroying) {
        return;
      }
      this.set('settings', settings);
      this.set('areSettingsLoaded', true);
    });
  }),

  initPolling: on('init', function () {
    this.get('polling').startPolling();
  }),

  initPubSub: on('init', function () {
    this.get('pubsub').listen();
  }),

  setVisibility(visibility) {
    this.set('settings.share', visibility);
    this.get('settings').save();
  },

  toggleShareActivity() {
    this.get('tracking').trackEvent({
      event: 'rich_presence_toggle',
      data: {
        login: Twitch.user.login(),
        action: this.get('settings.share_activity') ? 'disable' : 'enable'
      }
    });
    this.set('settings.share_activity', !this.get('settings.share_activity'));
    this.get('settings').save();
  },

  trackClickPresence(friend, targetUrl, activityInfo, uiContext) {
    this.get('tracking').trackEvent({
      event: 'friend_presence_click',
      data: {
        login: Twitch.user.login(),
        url: window.location.href,
        ui_context: uiContext,
        target_login: friend,
        target_url: targetUrl,
        target_action: activityInfo.type,
        target_channel: activityInfo.channel_login,
        target_hosted_channel: activityInfo.hosted_channel_login,
        target_game: activityInfo.game
      }
    });
  },

  updateLatestActivity(activity) {
    if (!activity) {
      activity = { type: 'none', game: null };
    }
    this.get('ping').setPresence(activity);
    this.set('polling.latestActivity', activity);
  }

});
