/* globals algoliasearch, Twitch */

import ApplicationAdapter from './application';
import env from 'web-client/config/environment';
import castToRSVP from 'web-client/utilities/cast-to-rsvp';
import injectService from 'ember-service/inject';
import { Stats } from 'client-event-reporter';

export default ApplicationAdapter.extend({
  search: injectService(),

  init() {
    this._super(...arguments);
    this.client = algoliasearch(env.algolia.id, env.algolia.key);
    this.stats = Stats.getInstance(env.environment, "web-client.services.algolia");
  },

  query(store, type, params = {}) {
    let algoliaQuery = castToRSVP(this.client.search(params));
    let stats = this.get("stats");

    return instrument(algoliaQuery, stats);
  }
});

function instrument(promise, stats) {
  let startTime = new Date();

  return promise.then(
    function(result) {
      let endTime = new Date();

      Twitch.geo.then(function(data) {
        stats.logCounter(`success.${data.region}`, 1);
        stats.logTimer(`success_duration.${data.region}`, endTime - startTime);
      });

      return result;
    },
    function(err) {
      let endTime = new Date();

      Twitch.geo.then(function(data) {
        stats.logCounter(`error.${data.region}`, 1);
        stats.logTimer(`error_duration.${data.region}`, endTime - startTime);
      });

      return err;
    });
}
