/*jshint browser:true, bitwise:false */
/*global console */

//= require rsvp
//= require underscore

//= require ./index.js

// Handles logic related to the event queue. This is necessary because the
// context is loaded in asynchronously so we need some sort of stroage of
// the events until the context is finished loading, at which time we can
// flush the queue.

(function (Twitch, $) {

  // TODO maybe refactor the queue logic out
  var EventHandler = function (contextLoader, additionalProperties) {
    var self = this;

    this.queue = [];
    RSVP.EventTarget.mixin(this.queue);

    // 'b' refers to adblock, intentionally obfuscated
    this.basicProperties = {
      b: Twitch.storage.get('b', {storage: 'sessionStorage'}) === 'true'
    };

    contextLoader.load(additionalProperties).then(function (basicProperties) {
      self.basicProperties = basicProperties;
      self.queue.on("eventInQueue", function (e) {
        // send event off of queue.
        var message = self.queue.pop();
        Twitch.tracking.spadeAndMixpanel.trackEvent(message.event,
          _.extend({}, self.basicProperties, message.properties)
        );
        if (self.queue.length > 0) {
          self.queue.trigger("eventInQueue");
        }
      });
      if (self.queue.length > 0) {
        self.queue.trigger("eventInQueue");
      }
    });
  };

  EventHandler.prototype.handle = function (eventName, properties) {
    properties = properties || {};
    this.queue.push({
      event : eventName,
      properties : properties
    });
    this.queue.trigger("eventInQueue");
  };

  Twitch.player.EventHandler = EventHandler;

})(Twitch, jQuery);
