/* globals Twitch, i18n */

import Component from 'ember-component';
import DeprecatedGameModel from 'web-client/models/deprecated-game';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import $ from 'jquery';

export default Component.extend({
  tagName: 'span',
  store: injectService(),
  tracking: injectService(),

  liveGameFollows: DeprecatedGameModel.find('liveFollows'),
  allGameFollows: DeprecatedGameModel.find('allFollows'),

  follow() { return this._api('follow'); },
  unfollow() { return this._api('unfollow'); },

  _api(kind) {
    let game = this.get('game');

    let promise = this.get('store').queryRecord('game', {
      kind: kind,
      src: 'directory',
      name: game.get('id')
    });

    promise.then(() => {
      if (this.isDestroyed) { return; }
      this.get('tracking').trackEvent({
        event: `${kind}-game`,
        data: {
          game: game.get('id'),
          src: 'directory'
        }
      });
    });

    return promise;
  },

  actions: {
    followClick: function () {
      if (!Twitch.user.isLoggedIn()) {
        $.login({mpSourceAction: 'game-follow-button'});

      } else {

        let game = this.get('game');

        this.set('game.isFollowing.isFollowing', true);
        if (game.get('channelCount') && game.get('channelCount') > 0) {
          this.get('liveGameFollows').addObject(game);
        }

        this.get('allGameFollows').addObject(game);

        this.follow().then(result => {
          if (result.get('channelCount') > 0) {
            game.mergeEmberDataModel(result);

            this.get('liveGameFollows').addObject(game);
          }
        });
      }
    },

    unfollowClick: function () {
      let game = this.get('game');

      this.set('game.isFollowing.isFollowing', false);
      this.get('liveGameFollows').removeObject(game);
      this.get('allGameFollows').removeObject(game);
      this.unfollow();
    }
  },

  isFollowing: computed('game.id', 'game.isFollowing.isLoaded', 'game.isFollowing.isFollowing', function () {
    if (Twitch.user.isLoggedIn()) {
      if (this.get('game.isFollowing') && !this.get('game.isFollowing.isLoaded')) {
        this.get('game.isFollowing').load();
      }
      return this.get('game.isFollowing.isFollowing');
    }
    return false;
  }),

  followText: i18n("Follow"),

  followingText: i18n("Following"),

  shouldRender: computed('isFollowing', function () {
    return this.get('isFollowing') !== undefined;
  })
});
