import Event from './Event';

export default class Dispatcher {
  constructor() {
    this.listenerChain = {};
  }
  
  listen(type, listener) {
    if( !listener instanceof Function ) throw { message: "Listener isn't a function" };
    if( !this.listenerChain[type] ) {
      this.listenerChain[type] = [listener];
    } else {
      this.listenerChain[type].push( listener );
    }
  }
  
  ignore(type, listener) {
    if( !this.hasListener( type ) ) return false;
    var totalListeners = this.listenerChain[type].length;
    for( var i = 0; i < totalListeners; i++ ) {
      if( this.listenerChain[type][i] == listener ) {
        this.listenerChain[type].splice( i, 1 );
      }
    }
  }
  
  notifyEvent(evt) {
    if( !this.hasListener( evt.type ) ) return false;
    var types = this.listenerChain[evt.type];
    var total = types.length;
    evt.target = this;
    for( var i = 0; i < total; ++i ) {
      if( types[i] !== undefined ) {
        types[i](evt);
      }
    }
    return true;
  }
  
  notify(type, params) {
    return this.notifyEvent( new Event(type, params) );
  }
  
  hasListener(type) {
    return (typeof this.listenerChain[type] != "undefined" );
  }
}
