export class ResMgr {

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

    // 跟随节点释放
    loadPrefab(name: string, parent: cc.Node): Promise<cc.Node>{
        return new Promise((resolve)=>{
            cc.resources.load(name, cc.Prefab, (err, res) => {
                if (res) {
                    let node = cc.instantiate(res);
                    parent.addChild(node);
                    res.addRef();
                    parent.on(cc.Node.EventType.CHILD_REMOVED, (child: cc.Node)=>{
                        if(child.uuid == node.uuid) {
                            res.decRef();
                        }
                    });
                    resolve(node);
                    return;
                }
                resolve(null);
            });
        });
    }

    getPrefab(name: string): Promise<cc.Prefab> {
        return new Promise((resolve)=>{
            cc.resources.load(name, cc.Prefab, (err, res) => {
                if (res) {
                    resolve(res);
                    return;
                }
                resolve(null);
            });
        });
    }

    createNode(res: cc.Prefab, parent: cc.Node){
        let node = cc.instantiate(res);
        parent.addChild(node);
        res.addRef();
        parent.on(cc.Node.EventType.CHILD_REMOVED, (child: cc.Node)=>{
            if(child.uuid == node.uuid) {
                res.decRef();
            }
        });

        return node;
    }
}