import DP from './DataPersistence';
class Messager {
    static mapPromise = {}
    constructor() {
    }
    
    trigger(msg, req) {
        let fun = DP.getAction(msg);
        if (typeof fun === 'function') {
            console.log('map:', Messager.mapPromise[msg]);
            let result = fun(req);
            if (result && result.then !== undefined) {
                result.then((res) => {
                    Messager.mapPromise[msg] && Messager.mapPromise[msg].forEach((callback) => {
                        try {
                            callback(req, res);
                        } catch (e) {
                            console.log(e);
                        }
                    });
                }).catch((e) => {
                    console.log(e)
                });
            } else { 
                Messager.mapPromise[msg] && Messager.mapPromise[msg].forEach((callback) => {
                    try {
                        callback(req, result);
                    } catch (e) {
                        console.log(e);
                    }
                });
            }
        } else {
            throw '[' + msg + ']消息事件在数据持久器还没有处理函数！';
        }
    }
    
    on(msg, callback) {
        if (!Messager.mapPromise[msg]) {
            Messager.mapPromise[msg] = new Map();
        }
        let key = Symbol();
        Messager.mapPromise[msg].set(key, callback);
        return key;
    }
    
    off(id) {
        Object.values(Messager.mapPromise).forEach((map) => {
            map.delete(id);
        })
    }
}
let instance = null;
if (!window._eldInstanceMessager) {
    instance = new Messager();
    instance.map = Messager.mapPromise;
    window._eldInstanceMessager = instance;
}
export default window._eldInstanceMessager;