/* globals Twitch */

import Ember from 'ember';
import StoreModel from 'web-client/models/store';
import computed from 'ember-computed';
import rename from 'web-client/utilities/rename';
import { GAME_NOT_FOUND } from 'web-client/utilities/game-names';
import logApiFailure from 'web-client/utilities/log-api-failure';

const { RSVP, observer, merge, inject } = Ember;

const DeprecatedGameModel = StoreModel.defineModel({
  relationships: {
    isFollowing() {
      return DeprecatedGameModel.find('isFollowing', {
        game: this.get('id')
      });
    }
  },

  deserialize: function (response) {
    let payload;

    if (response && response.game) {
      payload = merge(response, response.game);
    } else {
      payload = response || {};
    }

    return merge(
      rename(payload, {
        viewers: 'viewerCount',
        channels: 'channelCount'
      }), {
        id: payload.name || GAME_NOT_FOUND,
        url: Twitch.uri.game(payload.name) || ''
      }
    );
  },

  mergeEmberDataModel(edModel) {
    this.setProperties(edModel._internalModel._data);
  }
});


DeprecatedGameModel.reopenClass({
  findByName(api, name) {
    let url = `game/${encodeURIComponent(name)}`;

    return api.request('get', url).then((response) => {
      return DeprecatedGameModel.create(response.game);
    }, () => {
      return DeprecatedGameModel.create(null);
    });
  }
});


// Includes all games the user follows, whether live or not
//
DeprecatedGameModel.defineCollection('allFollows', {
  globals: inject.service(),
  api: inject.service(),

  lengthDidChange: observer('length', function () {
    if (this.get('length') > 0) {
      this.set('isFollowless', false);
    } else {
      this.set('isFollowless', true);
    }
  }),

  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({_total: 0, follows: []});
    }
    return this.get('api').request('get', '/api/users/:login/follows/games');
  },

  afterSuccess(response) {
    if (response._total > 0) {
      this.set('isFollowless', false);
    }
    else {
      this.set('isFollowless', true);
    }
    this.setContent(response.follows);
  },

  afterFail() {
    this.set('isFollowless', true);
    logApiFailure('game allFollows');
  }
});


DeprecatedGameModel.defineCollection('featured', {
  api: inject.service(),

  /* configuration & hooks */

  limit: 20,

  request() {
    return this.get('api').request('get', '/api/featured_games', {
      limit: this.limit,
      offset: this.get('content.length')
    });
  },

  afterSuccess(response) {
    // This is an example of the reponse for the featured games endpoint. We're including this here
    // to document this hard to reproduce API (there are often no featured games).
    //
    // this.setContent([
    //   {
    //     "featuredOnSidePanel": true, // Key additional attribute
    //     "featuredOnDirectory": true, // Key additional attribute
    //     "featuredOnFrontPage": true, // Key additional attribute
    //     "trackingUrls": {
    //       "trackingPixelUrl": "https://ad.doubleclick.net/ddm/ad/N5996.646586.TWITCH.TV/B9055367.125439106;sz=1x1;ord=[timestamp]?",
    //       "clickthroughUrl": "http://localhost.twitch.tv:4200/directory/game/Tom%20Clancy%27s%20Rainbow%20Six%3A%20Siege"
    //     },
    //     "game": {
    //       "name": "Tom Clancy's Rainbow Six: Siege",
    //       "_id": 460630,
    //       "giantbomb_id": 46562,
    //       "box": {
    //         "large": "http://static-cdn.jtvnw.net/ttv-boxart/Tom%20Clancy%27s%20Rainbow%20Six:%20Siege-272x380.jpg",
    //         "medium": "http://static-cdn.jtvnw.net/ttv-boxart/Tom%20Clancy%27s%20Rainbow%20Six:%20Siege-136x190.jpg",
    //         "small": "http://static-cdn.jtvnw.net/ttv-boxart/Tom%20Clancy%27s%20Rainbow%20Six:%20Siege-52x72.jpg",
    //         "template": "http://static-cdn.jtvnw.net/ttv-boxart/Tom%20Clancy%27s%20Rainbow%20Six:%20Siege-{width}x{height}.jpg"
    //       },
    //       "logo": {
    //         "large": "http://static-cdn.jtvnw.net/ttv-logoart/Tom%20Clancy%27s%20Rainbow%20Six:%20Siege-240x144.jpg",
    //         "medium": "http://static-cdn.jtvnw.net/ttv-logoart/Tom%20Clancy%27s%20Rainbow%20Six:%20Siege-120x72.jpg",
    //         "small": "http://static-cdn.jtvnw.net/ttv-logoart/Tom%20Clancy%27s%20Rainbow%20Six:%20Siege-60x36.jpg",
    //         "template": "http://static-cdn.jtvnw.net/ttv-logoart/Tom%20Clancy%27s%20Rainbow%20Six:%20Siege-{width}x{height}.jpg"
    //       },
    //       "_links": {}
    //     }
    //   }
    // ]);
    this.setContent(response);
  },

  afterFail() {
    logApiFailure('games');
  }

});


DeprecatedGameModel.defineCollection('isFollowing', {
  api: inject.service(),

  request() {
    return this.get('api').request('get', '/api/users/:login/follows/games/isFollowing', {
      name: this.get('game')
    });
  },

  afterSuccess() {
    this.set('isFollowing', true);
    this.set('isLoaded', true);
  },

  afterFail() {
    this.set('isFollowing', false);
    this.set('isLoaded', true);
  }

});


DeprecatedGameModel.defineCollection('liveFollows', {
  globals: inject.service(),
  api: inject.service(),
  contentSorting: ['viewers:desc'],
  sortedContent: computed.sort('content', 'contentSorting'),

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

    /** Under super heavy load, you can disable this heavy API request. */
    if (!Twitch.user.isLoggedIn() || disableFollowingDirectory) {
      return RSVP.resolve({_total: 0, follows: []});
    }
    return this.get('api').request('get', '/api/users/:login/follows/games/live');
  },

  afterSuccess(response) {
    if (response._total !== undefined) {
      this.set('total', response._total);
    }
    this.setContent(response.follows);
  },

  afterFail() {
    logApiFailure('game liveFollows');
  }

});

export default DeprecatedGameModel;
