/**
 * 局部的事件收发器
 */
export default class Dispatcher {
    /**
     * 事件回调池
     */
    private callbackPool: any = {};

    /**
     * 事件作用域池
     */
    private thisObjPool: any = {};

    /**
     *
     * @param name 事件名
     * @param callback 回调
     * @param thisObj 作用域
     */
    public addEvent(name: string | number, callback, thisObj: any): void {
        if(!this.callbackPool[name]) {
            this.callbackPool[name] = [];
            this.thisObjPool[name] = [];
        }

        const index: number = this.callbackPool[name].indexOf(callback);
        const thisObjIndex: number = this.thisObjPool[name].indexOf(thisObj);
        if(index != -1 && thisObjIndex != -1) {
            this.callbackPool[name][index] = callback;
            this.thisObjPool[name][index] = thisObj;
        } else {
            this.callbackPool[name].push(callback);
            this.thisObjPool[name].push(thisObj);
        }
    }

    /**
     *
     * @param name 事件名
     * @param callback 回调
     * @param thisObj 作用域
     */
    public removeEvent(name: string | number, callback, thisObj?: any): void {
        if(this.callbackPool[name]) {
            const index: number = this.callbackPool[name].indexOf(callback);
            if(index != -1) {
                this.callbackPool[name].splice(index, 1);
                this.thisObjPool[name].splice(index, 1);
            }
        }
    }

    /**
     * 派发事件
     * @param name 事件名
     * @param args 任意参数
     */
    public dispatchEvent(name: string | number, ...args): void {
        const callbacks: Function[] = this.callbackPool[name];
        const thisObjs: any = this.thisObjPool[name];
        if(callbacks) {
            let i = 0;
            const len: number = callbacks.length;
            for(i; i < len; i++) {
                callbacks[i].apply(thisObjs[i], args);
            }
        }
    }
}