import { EConfigConst, jsonNames } from "./ConfigDef";

export class ConfigMgr {
    private static _inst: ConfigMgr;
    public static get inst(): ConfigMgr {
        if (this._inst == null) {
            this._inst = new ConfigMgr();
        }
        return this._inst;
    }

    config: cc.AssetManager.Cache = new cc.AssetManager.Cache();
    init(): Promise<any> {

        let arr = jsonNames.map(v=>{ return 'json/' + v + '.json'});
        let task = [];
        arr.forEach((v,k)=>{
            let p = new Promise((resolve:any)=>{
                cc.assetManager.loadRemote(v, (err, res: cc.JsonAsset)=>{
                    if(res){
                        this.config.add(jsonNames[k], res.json);
                        cc.assetManager.releaseAsset(res);
                    }
                    resolve();
                })
            });
            task.push(p);
        })
        return Promise.all(task);
    }

    getCfgKeys(e: EConfigConst){
        let key = jsonNames[e];
        let cfg = this.config.get(key);
        return Object.keys(cfg);
    }

    getCfgById(e: EConfigConst, id){
        let key = jsonNames[e];
        let cfg = this.config.get(key);
        return cfg[id];
    }

    getCfgClassById<T>(e: EConfigConst, id, objType: {new(id,data): T}):T {
        let key = jsonNames[e];
        let cfg = this.config.get(key);
        return new objType(id, cfg[id]);
    }
}