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

import FishUI from '../../../fish/script/FishUI'
import ScorePrefab from '../prefab/ScorePrefab'

const { ccclass, property } = _decorator

@ccclass('ScoreManager')
export default class ScoreManager extends Component {
  public static instance: ScoreManager = null
  @property({ type: Prefab })
  private scrorePrefab: Prefab | null = null

  private scorePool: NodePool

  onLoad() {
    ScoreManager.instance = this
    this.scorePool = new NodePool()
  }

  // 添加积分
  public addScore(score: number, p: Vec2) {
    const scorePrefab: ScorePrefab = this.createScore(score)
    this.node.addChild(scorePrefab.node)
    scorePrefab.node.setPosition(new Vec3(p.x, p.y, 0))
    scorePrefab.init(score)
    scorePrefab.playMoveEffect(new Vec2(-472.398, -547.481), () => {
      this.destroyScore(scorePrefab)
      // 本地不在添加积分
      // FishUI.instance.jf_score += score
      // FishUI.instance.refreshScore()
    })
  }

  // 创建积分
  private createScore(score: number): ScorePrefab {
    let scoreNode: Node
    if (this.scorePool && this.scorePool.size() > 0) scoreNode = this.scorePool.get()
    else scoreNode = instantiate(this.scrorePrefab)

    return scoreNode.getComponent(ScorePrefab)
  }

  // 销毁积分
  private destroyScore(scorePrefab: ScorePrefab) {
    this.scorePool.put(scorePrefab.node)
  }

  onDisable() {}

  onDestroy() {
    ScoreManager.instance = null
  }
}
