import { instantiate } from "cc";
import { Prefab } from "cc";
import AB from "../base/AB";

export class PoolType {
  public static readonly POG = 1;
  public static readonly GEM = 2;
}

export default class PoolM {
  private static _ins: PoolM;
  public static get ins(): PoolM {
    if (!PoolM._ins) {
      PoolM._ins = new PoolM();
    }
    return PoolM._ins;
  }

  private pool: Map<number, any> = new Map();

  private prefab: Map<number, Prefab> = new Map();

  public async get(name: number, prefab: Prefab): Promise<Node> {
    // if (!this.pool.has(name)) {
    //   this.pool.set(name, instantiate(prefab));
    // }
    // return this.pool.get(name);
    //@ts-ignore
    let node: Node = instantiate(prefab);
    return node;
  }

  public put(name: number, node: Node) {
    if (this.pool.has(name)) {
      this.pool.get(name).destroy();
    }
    this.pool.set(name, node);
  }

  public async getGem(): Promise<Node> {
    return this.getByPath(PoolType.GEM, "prefab/fly/gem");
  }

  public async getPog() {
    return this.getByPath(PoolType.POG, "prefab/fly/pog");
  }

  public async getByPath(key: number, path: string): Promise<Node> {
    if (!this.prefab.has(key)) {
      let p = await AB.ins.loadPrefab(path);
      this.prefab.set(key, p);
    }
    return this.get(key, this.prefab.get(key));
  }
}
