import Service from 'ember-service';
import Ember from 'ember';

const { inject } = Ember;
const MAX_LENGTH = 10;

export default Service.extend({
  store: inject.service(),
  api: inject.service(),

  _maxLength: MAX_LENGTH,

  _createRecord(store, gameId, timestamp) {
    return store.createRecord('watched-game', {
      id: gameId,
      timestamp: timestamp
    });
  },

  _findGameId(gameName) {
    let url = `search/games?type=suggest&q=${gameName}`;

    return this.get('api').request('get', url).then((response) => {
      if (this.isDestroyed) { return; }
      let foundGame = response.games.find(function (game) {
        return game.name === gameName;
      });

      return foundGame && foundGame._id;
    });
  },

  _gameNotFound(store, gameId, timestamp, watchedGames) {
    let length = watchedGames.get('length');

    if (length < this.get('_maxLength')) {
      return this._createRecord(store, gameId, timestamp).save();
    }
    let oldestGame = watchedGames.sortBy('timestamp').get('firstObject');

    oldestGame.deleteRecord();
    return oldestGame.save().then(() => {
      return this._createRecord(store, gameId, timestamp).save();
    });
  },

  _addGame(gameId) {
    if (!gameId) {
      return;
    }

    let store = this.get('store');
    let timestamp = new Date();

    return store.findAll('watched-game').then((watchedGames) => {
      let watchedGame = watchedGames.findBy('id', gameId);

      if (watchedGame) {
        watchedGame.set('timestamp', timestamp);
        return watchedGame.save();
      }
      return this._gameNotFound(store, gameId, timestamp, watchedGames);
    });
  },

  addGame(gameName) {
    return this._findGameId(gameName).then((gameId) => {
      if (gameId) {
        return this._addGame(gameId.toString());
      }
    });
  }
});
