import Service from 'ember-service';
import injectService from 'ember-service/inject';

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

  ddVersion: '',

  isEnabled: false,

  serializedChampData: [],

  champQuery: null,

  init() {
    this._super(...arguments);
    this._getChampions();
  },

  // TODO: champion based on locale, accept `language` as a param
  _getChampions() {
    this.get('api').request('get', '/api/lol/champions').then(response => {
      this.set('ddVersion', response.version);
      this._serializeChampData(response);
    });
  },

  _serializeChampData(response) {
    let data = response['data'] || {};
    let keys = Object.keys(data);
    let ddVersion = this.get('ddVersion');
    let allChampTags = {};
    let serialized = keys.map(champ => {
      let champTags = {};
      data[champ]['tags'].forEach(tag => {
        allChampTags[tag.toLowerCase()] = true;
        champTags[tag.toLowerCase()] = true;
      });

      let sprite = data[champ]['image']['sprite'];
      return {
        key: champ,
        name: data[champ]['name'],
        spriteSrc: `https://ddragon.leagueoflegends.com/cdn/${ddVersion}/img/sprite/${sprite}`,
        spriteWidth: data[champ]['image']['w'],
        spriteHeight: data[champ]['image']['h'],
        spritePos: `-${data[champ]['image']['x']}px -${data[champ]['image']['y']}px`,
        tags: champTags
      };
    });

    this.set('champTags', allChampTags);

    // Sort on display name, not key name (eg. `Wukong` have a keyname of `MonkeyKing`)
    let serializedChampData = serialized.sort((x,y) => {
      return ((x.name < y.name) ? -1 : ((x.name > y.name) ? 1 : 0));
    });
    this.set('serializedChampData', serializedChampData);
  }

});
