import { Component, Node, NodePool, Prefab, Vec2, Vec3, _decorator, instantiate } from 'cc'

import FishNetBase from '../../../fish/script/FishNetBase'

const { ccclass, property } = _decorator

// 鱼网管理类
@ccclass('FishNetManager')
export default class FishNetManager extends Component {
  public static instance: FishNetManager = null
  @property({ type: [Prefab] })
  private netPrefabList: Prefab[] | [] = []

  private fishNetPool: Array<NodePool> = []

  onLoad() {
    FishNetManager.instance = this
  }

  // 添加鱼网
  public addFishNet(netType: number, p: Vec2) {
    const fishNet: FishNetBase = this.createFishNet(netType)
    this.node.addChild(fishNet.node)
    fishNet.node.setPosition(new Vec3(p.x, p.y, 0))
    fishNet.playMv()
  }

  // 创建鱼网
  private createFishNet(netType: number) {
    let fishNetNode: Node
    if (this.fishNetPool[netType] && this.fishNetPool[netType].size() > 0) {
      fishNetNode = this.fishNetPool[netType].get()
    } else {
      fishNetNode = instantiate(this.netPrefabList[netType])
    }

    fishNetNode.getComponent(FishNetBase).netType = netType
    return fishNetNode.getComponent(FishNetBase)
  }

  // 销毁鱼网
  public destroyFishNet(fishNet: FishNetBase) {
    if (!this.fishNetPool[fishNet.netType]) {
      this.fishNetPool[fishNet.netType] = new NodePool()
    }

    this.fishNetPool[fishNet.netType].put(fishNet.node)
  }

  onDestroy() {
    FishNetManager.instance = null
  }
}
