import DP from './DataPersistence';
class Messager {
    constructor() {
        this.mapPromise = {};
    }
    
    static getInstance(){
        if(window.top._coneMessager == null){
            window.top._coneMessager = new Messager();
        }
        return window.top._coneMessager;
    }
    
    trigger(msg, req) {
        let fun = DP.getAction(msg);
        if (typeof fun === 'function') {
            let result = fun(req);
            let handlers = this.mapPromise[msg];
            if (result && result.then !== undefined) {
                result.then((res) => {
                    this._call(handlers, req, res);
                }).catch((e) => {
                    console.log(e)
                });
            } else { 
                this._call(handlers, req, result);
            }
        } else {
            let handlers = this.mapPromise[msg];
            this._call(handlers, req, null);
        }
    }
    _call(handlers, req, result){
        if(handlers){
            let _list = [].concat(handlers);
            for(let i=0,len=_list.length;i<len; i++){
                let h = _list[i];
                if(h && typeof h.callback == 'function'){
                    try{
                        h.callback(req, result);
                    }
                    catch (e) {
                        console.log(e);
                    }
                }
            }
        }
    }
    
    on(msg, callback) {
        let handlers = this.mapPromise[msg];
        if (!handlers) {
            handlers = [];
            this.mapPromise[msg] = handlers;
        }
        let key = Symbol();
        if(this._has(handlers, key)==false){
            handlers.push({key:key, callback:callback});
        }
        return key;
    }
    _has(handlers, id){
        let result = false;
        if(handlers && id){
            for(let i=handlers.length-1;i>=0; i--){
                let item = handlers[i];
                if(item.key==id){
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
    _remove(handlers, id){
        if(handlers && id){
            for(let i=handlers.length-1;i>=0; i--){
                let item = handlers[i];
                if(item.key==id){
                    handlers.splice(i, 1);
                    break;
                }
            }
        }
    }
    
    off(id) {
        Object.values(this.mapPromise).forEach((handlers) => {
            this._remove(handlers, id);
        })
    }
}
export default Messager.getInstance();