/**
 * @description 对象池管理类
 * @author 邹勇
 */
export default class PoolSystem {
    constructor() {
        
    }

    private poolList: Map<string, cc.NodePool>;

    public async init(pools: { url: string, num: number }[]) {
        this.poolList = new Map<string, cc.NodePool>();
        for (let i = 0; i < pools.length; i++) {
            let item = pools[i];
            let prefab = await mk.loader.load(item.url, cc.Prefab);
            if (!prefab) {
                console.log("没有找到该prefab", item.url);
                continue;
            }
            var pool: cc.NodePool = new cc.NodePool();
            for (let i = 0; i < item.num; ++i) {
                let node = cc.instantiate(prefab);
                pool.put(node);
            }
            let arr = item.url.split("/");
            this.poolList.set(arr[arr.length - 1], pool);
        }
    }

    /**
    * 获取prefab的node
    * @param url
    * @returns 
    */
    public async getPrefab(url: string) {
        let arr = url.split("/");
        let name = arr[arr.length - 1];
        var pool = this.poolList.get(name);
        let node: cc.Node = null;
        if (pool && pool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            node = pool.get();
        } else {
            let prefab = await mk.loader.load(url, cc.Prefab);
            node = cc.instantiate(prefab);
            pool && pool.put(node);
        }
        return node;
    }

    /**
     * 退回对象池
     * @param name prefab名字
     * @param node 
     */
    return(name, node: cc.Node) {
        // node.destroy();
        node.removeFromParent();
        let pool = this.poolList[name];
        if (pool) {
            pool.put(node);
        }
    }

    clearPool(name) {
        if (this.poolList[name]) {
            this.poolList[name].clear();
        }
    }

}