import { ResRelease } from "./resRelease";

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();

                    node.addComponent(ResRelease).call = ()=>{
                        res.decRef();
                    }
                    resolve(node);
                    return;
                }
                else{
                    cc.log(err);
                }
                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;
                }
                else{
                    cc.log(err);
                }
                resolve(null);
            });
        });
    }

    createNode(res: cc.Prefab, parent: cc.Node){
        let node = cc.instantiate(res);
        parent.addChild(node);
        res.addRef();
        node.addComponent(ResRelease).call = ()=>{
            res.decRef();
        }

        return node;
    }

    loadAni(name: string, node: cc.Node): Promise<cc.AnimationClip>{
        return new Promise((resolve)=>{
            cc.resources.load(name, cc.AnimationClip, (err, res) => {
                if (res) {
                    res.addRef();

                    node.addComponent(ResRelease).call = ()=>{
                        res.decRef();
                    }
                    resolve(res);
                    return;
                }
                else{
                    cc.log(err);
                }
                resolve(null);
            });
        });
    }

    loadAniArr(name: string[], node: cc.Node): Promise<cc.AnimationClip[]>{
        return new Promise((resolve)=>{
            cc.resources.load(name, cc.AnimationClip, (err, res) => {
                if (res) {
                    res.forEach(v=> v.addRef());
                    node.addComponent(ResRelease).call = ()=>{
                        res.forEach(v=> v.decRef());
                    }
                    resolve(res);
                    return;
                }
                else{
                    cc.log(err);
                }
                resolve(null);
            });
        });
    }
}