import Bee from "./Bee";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Hive extends cc.Component {
  static instance: Hive;
  @property(cc.Prefab) beePrefab: cc.Prefab = null;
  @property(cc.Node) dog: cc.Node = null;

  refreshTimer: number = 0.2;
  isSpawnable: boolean = false;
  timer: number = 0;
  beeAmount: number = 10;
  currentBeeAmount: number = 0;

  spawnBees() {
    if (!this.isSpawnable) return;
    if (this.timer > 0) return;
    if (this.currentBeeAmount >= this.beeAmount) return;

    this.timer = this.refreshTimer;
    var bee = cc.instantiate(this.beePrefab);
    let nodeWorldPosition = this.node.convertToWorldSpaceAR(cc.Vec2.ZERO);
    let nodeCanvasPosition =
      this.node.parent.parent.convertToNodeSpaceAR(nodeWorldPosition);
    bee.parent = this.node.parent.parent;
    bee.position = cc.v3(nodeCanvasPosition.x, nodeCanvasPosition.y);
    bee.getComponent(Bee).targetPosition = this.dog;
    bee.getComponent(Bee).fly();
    this.currentBeeAmount++;
  }

  protected update(dt: number): void {
    this.timer -= dt;
    this.spawnBees();
  }

  protected onLoad(): void {
    Hive.instance = this;
  }
}
