import { Prefab, resources, instantiate, Node } from "cc";

export class ObjPool {

    private static _pools: Map<string, Node[]> = new Map();
    private static prefabs: Map<string, Prefab> = new Map();

    private static prefabType: Map<string, Prefab[]> = new Map();

    private static load(folder: string) {
        return new Promise<boolean>((resolve, reject) => {
            resources.loadDir(`Prefabs/${folder}`, Prefab, (err: Error | null, prefabs: Prefab[]) => {
                if(err) {
                    reject(false);
                }
                else {
                    prefabs.forEach(prefab => {
                        this.prefabs.set(prefab.data.name, prefab);
                    });
                    this.prefabType.set(folder, prefabs);
                    resolve(true);
                }
            });
        });
    }

    static getNode(nodeName: string, prefab: Prefab | null = null) {
        if(!this._pools.has(nodeName)) {
            this._pools.set(nodeName, []);
        }
        let lst = this._pools.get(nodeName)!;
        let node!: Node;
        if(lst.length === 0) {
            node = instantiate(prefab || this.prefabs.get(nodeName)!);
        }
        else {
            node = lst!.pop()!;
        }
        node.active = true;
        return node;
    }

    static putNode(node: Node) {
        if(this._pools.get(node.name)!.indexOf(node) >= 0) {
            debugger;
        }
        node.active = false;
        this._pools.get(node.name)!.push(node);
    }
}