import GamePlay from "../Controllers/GamePlay";
import SoundController from "../Controllers/SoundController";
import LocalStorage from "../Data/LocalStorage";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Dog extends cc.Component {
  static instance: Dog;
  attacked = false;
  currentSkin: string;

  protected onLoad(): void {
    Dog.instance = this;
    this.currentSkin = LocalStorage.getCurrentSkinPlayer();
  }

  onBeginContact(contact, selfCollider, otherCollider) {
    if (GamePlay.instance.isCompleted) return;
    if (!this.attacked && otherCollider.tag == 1) {
      this.attacked = true;
      GamePlay.instance.isGameover = true;
      SoundController.playNoLoopSound(SoundController.instance.sounds[9]);
      this.node.getComponent(cc.Animation).play(`${this.currentSkin}Hurt`);
    }
    if (otherCollider.tag == 3) {
      SoundController.playNoLoopSound(SoundController.instance.sounds[7]);
      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();
          GamePlay.instance.onReloadLevel();
        })
        .start();
      this.node.getComponent(cc.RigidBody).linearVelocity = cc.Vec2.ZERO;
      this.node.getComponent(cc.Animation).pause();
      this.node.getComponent(cc.RigidBody).fixedRotation = true;
    }
  }
}
