import {
  _decorator,
  Prefab,
  Node,
  resources,
  NodePool,
  instantiate,
  error,
  sp,
} from "cc";

const { ccclass, property } = _decorator;

export interface IPoolItem {
  key: string;
  prefabPath: string;
}
@ccclass
export default class PoolMgr {
  pools: any = {};
  prefabs: any = {};

  pre_bullets: Prefab[] = [];

  private static _instance: PoolMgr = null;
  public static Instance(): PoolMgr {
    if (PoolMgr._instance == null) PoolMgr._instance = new PoolMgr();
    return PoolMgr._instance;
  }

  loadPrefabs(items: IPoolItem[]) {
    for (let i = 0; i < items.length; i++) {
      let item = items[i];
      resources.load(item.prefabPath, Prefab, (err, ret) => {
        if (err) {
          console.error(err);
          return;
        }
        this.initPool(item.key, ret, 11);
      });
    }
  }

  initPool(key: any, prefab: Prefab, count: number) {
    this.prefabs[key] = prefab;
    this.pools[key] = new NodePool();
    for (var i = 0; i < count; ++i) {
      this.pools[key].put(instantiate(prefab));
    }
  }

  get(key: any): Node {
    if (this.pools[key] == null) {
      error("没有" + key);
      return null;
    }
    if (this.pools[key].size() > 0) {
      var node = this.pools[key].get();
      var spine = node.getChildByName("spine");
      if (spine) {
        spine.getComponent(sp.Skeleton).paused = false;
      }
      return node;
    } else return instantiate(this.prefabs[key]);
  }

  put(key: any, node: Node) {
    this.pools[key].put(node);
  }
}
