const { ccclass, property } = cc._decorator;

@ccclass
export default class Bubble extends cc.Component {
  static instance: Bubble;
  @property(cc.Vec2)
  fallSpeed: cc.Vec2 = cc.v2(0, 1);
  @property(cc.Prefab)
  bubblePrefab: cc.Prefab = null;

  private currentSpawnIndex: number = 0;
  private totalNodes: number = 10;

  onLoad() {
    Bubble.instance = this;
    this.schedule(
      () => {
        if (this.currentSpawnIndex < this.totalNodes) {
          this.spawnBubble();
          this.currentSpawnIndex++;
        }
      },
      0.1,
      this.totalNodes - 1
    );
  }

  update(dt: number) {
    this.node.children.forEach((bubblePrefab) => {
      const a = Math.random() * 5;
      bubblePrefab.y += this.fallSpeed.y * a * 50 * dt;

      if (bubblePrefab.y > this.node.height / 2) {
        const randomX = this.getRandomX();
        const randomY = -this.node.height / 2 - 50;
        bubblePrefab.setPosition(randomX, randomY);
      }
    });
  }

  getRandomX(): number {
    return (Math.random() - 0.5) * this.node.width;
  }

  spawnBubble() {
    const randomX = (Math.random() - 0.5) * this.node.width;
    let newFood = cc.instantiate(this.bubblePrefab);
    this.node.addChild(newFood);
    newFood.setPosition(cc.v2(randomX, this.node.height / 2));
    newFood.opacity = 100;
  }
}
