import Service from 'ember-service';
import RSVP from 'rsvp';
import injectService from 'ember-service/inject';
import { searchObject, TYPES, VIDEO_TYPE } from 'web-client/services/search';

export default Service.extend({
  store: injectService(),

  init() {
    this._super(...arguments);
    this.games = [];
    this.videos = [];
    this.users = [];
    this.channels = [];
    this.simulateNetworkErrors = false;
  },

  queryTopResults(term = '') {
    if (this.simulateNetworkErrors) {
      return RSVP.reject({});
    }

    let games = this.games.filter((game) => game.name.indexOf(term) !== -1);
    let videos = this.videos.filter((video) => video.title.indexOf(term) !== -1);
    let users = this.users.filter((user) => user.name.indexOf(term) !== -1);
    let channels = this.channels.filter((channel) => channel.name.indexOf(term) !== -1);

    let filteredResults = [{
      index: 'game',
      hits: games,
      nbHits: games.length,
      hitsPerPage: 1
    }, {
      index: TYPES[VIDEO_TYPE].indexName,
      hits: videos,
      nbHits: videos.length,
      hitsPerPage: 1
    }, {
      index: 'user',
      hits: users,
      nbHits: users.length,
      hitsPerPage: 1
    }, {
      index: 'live_channel',
      hits: channels,
      nbHits: channels.length,

      hitsPerPage: 1
    }];

    let unfilteredResults = filteredResults.map(({ index, hits, nbHits }) => {
      return { index, hits, nbHits, hitsPerPage: 0 };
    });

    let results = [...filteredResults, ...unfilteredResults];
    this.get('store').pushPayload('search', { results });

    return RSVP.resolve(searchObject(this.get('store')));
  },

  queryForType(type, term) {
    if (this.simulateNetworkErrors) {
      return RSVP.reject({});
    }

    let hits = this[type].filter((model) => {
      let modelName = model.name || model.title;
      return modelName.indexOf(term) !== -1;
    });

    let results = [{
      index: TYPES[type].indexName,
      hits,
      nbHits: hits.length,
      hitsPerPage: 1
    }];

    this.get('store').pushPayload('search', { results });
    return RSVP.resolve(searchObject(this.get('store')));
  }
});
