/* globals Twitch */

import Ember from 'ember';
import StoreModel from 'web-client/models/store';
import computed from 'ember-computed';

const { RSVP, inject } = Ember;

const HostModel = StoreModel.defineModel({
  expiration: 60000, // 1 minute

  deserialize: function (data) {
    data.id = data.name;
    data.game = data.target.meta_game;
    return data;
  },

  /** computed properties */
  gameUrl: computed('game', function () {
    return Twitch.uri.game(this.get('game'));
  }),

  gameBoxart: computed('game', function () {
    return Twitch.uri.gameBoxArtJpg(this.get('game'));
  }),

  hostHref: computed('id', function () {
    return Twitch.uri.channel(this.get('id'));
  })
});

HostModel.defineCollection('following', {
  globals: inject.service(),
  api: inject.service(),
  limit: 40,

  request() {
    let globals = this.get('globals');
    let disableFollowingDirectory = globals.get('disableFollowingDirectory');

    /** Under super heavy load, you can disable this heavy API request. */
    if (!Twitch.user.isLoggedIn() || disableFollowingDirectory) {
      return RSVP.resolve({hosts: [], _total: 0});
    }
    let opts = {limit: this.limit, offset: this.get('content.length')};
    return this.get('api').request('get', '/api/users/:login/followed/hosting', opts);
  },

  afterSuccess(response) {
    this.setContent(response.hosts);
    this.set('total', response._total);
  }
});

export default HostModel;
