import GamePlay from "../Controllers/GamePlay";
import StageController from "../Controllers/StageController";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Bee extends cc.Component {
  static instance: Bee;

  flySpeed: number = 100;
  targetPosition: cc.Node = null;
  flying = false;
  timer: number = 0;
  velocity: cc.Vec2 = cc.v2(0, 0);

  onBeginContact(contact, selfCollider, otherCollider) {
    if (otherCollider.tag == 1 || otherCollider.tag == 0) {
      this.node.getComponent(cc.RigidBody).linearVelocity = cc.v2(
        this.velocity.x,
        this.velocity.y
      );
      this.timer = 0.3;
      let arrayTarget = StageController.instance.dogList;
      let randomIndex = Math.floor(Math.random() * arrayTarget.length);
      this.targetPosition = arrayTarget[randomIndex];
    }
    if (otherCollider.tag == 3) {
      let effect = cc.instantiate(GamePlay.instance.fadePrefab);
      effect.parent = this.node;
      effect.position = this.node.convertToNodeSpaceAR(
        this.node.parent.convertToWorldSpaceAR(this.node.position)
      );
      cc.tween(this.node)
        .to(1, { opacity: 0 })
        .call(() => {
          this.node.destroy();
        })
        .start();
      this.node.getComponent(cc.RigidBody).linearVelocity = cc.Vec2.ZERO;
      this.node.getComponent(cc.Animation).pause();
      this.node.getComponent(cc.RigidBody).fixedRotation = true;
    }
  }

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

  protected update(dt: number): void {
    this.timer -= dt;
    if (this.targetPosition && this.flying) {
      var deltaX = this.targetPosition.x - this.node.x;
      var deltaY = this.targetPosition.y - this.node.y;
      var direction = cc.v3(deltaX, deltaY);
      this.velocity = cc.v2(
        direction.x * dt * this.flySpeed,
        direction.y * dt * this.flySpeed
      );
      let distance = direction.mag();
      let angle = (Math.atan2(direction.y, direction.x) * 180) / Math.PI;

      this.node.angle = angle;
      if (distance > 1 && this.timer < 0) {
        this.node.getComponent(cc.RigidBody).linearVelocity = this.velocity;
      }
    }
  }

  fly() {
    this.flying = true;
  }
}
