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

export default Component.extend({
  tagName: 'div',
  // NOTICE: The login service is deprecated, plesase use the session service.
  // See app/services/SESSION.md for more details.
  login: injectService(),
  store: injectService(),
  tracking: injectService(),
  isFollowing: computed.alias('deprecatedGame.isFollowing.isFollowing'),

  follows: {
    // 'live' and 'all' are not `load`-ed because it should already have been loaded by the time
    // this component renders.
    live: DeprecatedGameModel.find('liveFollows'),
    all: DeprecatedGameModel.find('allFollows')
  },

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

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

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

  deprecatedGame: computed(function () {
    return DeprecatedGameModel.create({
      game: {
        name: this.get('game.id'),
        logo: this.get('game.logo').getProperties('small', 'medium', 'large', 'template'),
        box: this.get('game.box').getProperties('small', 'medium', 'large', 'template')
      }
    });
  }),

  actions: {
    followClick: function () {
      let deprecatedGame = this.get('deprecatedGame'),
          follows = this.get('follows');

      if (this.get('isFollowing')) {
        this.set('isFollowing', false);
        follows.live.removeObject(deprecatedGame);
        follows.all.removeObject(deprecatedGame);
        this.unfollow();
      } else {
        follows.live.addObject(deprecatedGame);
        follows.all.addObject(deprecatedGame);
        this.set('isFollowing', true);
        this.follow();
      }
    }
  }
});
