// Generated by CoffeeScript 1.4.0
(function() {
  var MessageHandler, exports,
    __slice = [].slice;

  exports = window;

  /*
   * Generic message handling class.
  */


  MessageHandler = (function() {

    function MessageHandler() {
      var _ref;
      this._log = getLogger(this);
      if ((_ref = this._handlers) == null) {
        this._handlers = {};
      }
      this._mergedHandlers = [];
    }

    MessageHandler.prototype.listenTo = function(emitter) {
      var type, _results,
        _this = this;
      _results = [];
      for (type in this._handlers) {
        _results.push(emitter.on(type, function() {
          var args;
          args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
          return _this.handle.apply(_this, [type].concat(__slice.call(args)));
        }));
      }
      return _results;
    };

    MessageHandler.prototype.merge = function(handlerObject) {
      return this._mergedHandlers.push(handlerObject);
    };

    MessageHandler.prototype.registerHandlers = function(handlers) {
      var handler, type, _results;
      _results = [];
      for (type in handlers) {
        handler = handlers[type];
        _results.push(this.registerHandler(type, handler));
      }
      return _results;
    };

    MessageHandler.prototype.registerHandler = function(type, handler) {
      return this._handlers[type] = handler;
    };

    MessageHandler.prototype.handle = function() {
      var handler, params, type, _i, _len, _ref, _ref1, _results;
      type = arguments[0], params = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      this.type = type;
      this.params = params;
      assert(this.canHandle(this.type));
      if ((_ref = this._handlers[this.type]) != null) {
        _ref.apply(this, this.params);
      }
      _ref1 = this._mergedHandlers;
      _results = [];
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        handler = _ref1[_i];
        if (handler.canHandle(this.type)) {
          _results.push(handler.handle.apply(handler, [this.type].concat(__slice.call(this.params))));
        }
      }
      return _results;
    };

    MessageHandler.prototype.canHandle = function(type) {
      var handler, _i, _len, _ref;
      if (type in this._handlers) {
        return true;
      }
      _ref = this._mergedHandlers;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        handler = _ref[_i];
        if (handler.canHandle(type)) {
          return true;
        }
      }
      return false;
    };

    return MessageHandler;

  })();

  exports.MessageHandler = MessageHandler;

}).call(this);
