import { changeScene } from "../../module/ctrls";
import { Scene } from "../../module/views/Scene";
import { Tools } from "../tools/Tools";
import UI from "../tools/UI";
import { RES } from '../../module/RES';
import Button = FYGE.Button;
import Container = FYGE.Container;
import Shape = FYGE.Shape;
import Sprite = FYGE.Sprite;
import TEXT_ALIGN = FYGE.TEXT_ALIGN;
import TextField = FYGE.TextField;
import VERTICAL_ALIGN = FYGE.VERTICAL_ALIGN;
import Texture = FYGE.Texture;
import FrameAni = FYGE.FrameAni;

/** 初始坠落步长 */
const FIAL_STEP = 4
/** 初始跳跃步长 */
const JUMP_STEP = 19
/** 最大跳跃步长 */
const JUMP_MAX_STEP = JUMP_STEP - 8
/** 坠落速率 */
const FIAL_MUI = 0.4

export class Bird extends Container {
  /** 坠落步长 */
  failStep = FIAL_STEP

  /** 跳跃步长 */
  jumpStep = JUMP_STEP

  /** 游戏玩家帧动画 */
  player: FrameAni = null

  /** 游戏是否结束 */
  isGameOver:boolean = false

  constructor() {
    super()
    this.initUi()
  }

  async initUi() {
    const birdAni = [
      RES.getRes('redbird_upflap.png'),
      RES.getRes('redbird_midflap.png'),
      RES.getRes('redbird_downflap.png'),
    ]
    this.player = new FrameAni(birdAni)
    this.player.play(0)
    this.anchorX = this.width / 2
    this.anchorY = this.height / 2
    // this.player.scale.x = 3
    // this.player.scale.y = 3
    this.addChild(this.player)
  }

  /** 旋转小鸟位置 */
  birdRotation() {
    if (this.failStep > 0) {
      this.rotation = Math.min(80, this.failStep * 2)
    } else if (this.failStep < 0) {
      this.rotation = -25
    } else {
      this.rotation = 0
    }
  }

  /**
   * 小鸟坠落
   * @param acceleration 加速比
   */
  fail(rate) {
    const acceleration = FIAL_MUI
    if(this.isGameOver) return
    this.failStep += acceleration * rate
    // console.log(this.failStep * rate)
    this.y = Math.max(this.y + (this.failStep * rate) , 0)
    if (this.y == 0) {
      this.reset()
    }
    this.birdRotation()
  }

  /** 小鸟跳跃 */
  jump(rate) {
    if(this.isGameOver) return
    if (this.y <= 0) return
    // console.log('jump')
    this.failStep = Math.max(this.failStep - this.jumpStep,-JUMP_MAX_STEP)
  }

  /** 重置 */
  reset() {
    this.failStep = FIAL_STEP
    this.jumpStep = JUMP_STEP
  }

  /** 游戏结束 */
  gameOver() {
    this.reset()
    this.isGameOver = true
    this.rotation = 0
    this.player.reset(this.player.getCurrentFrame())
  }

  destroy() {
    super.destroy();
  }

}