import { _decorator, Animation, AudioSource, Collider2D, Component, Contact2DType, Node, RigidBody2D, Vec2, Vec3 } from 'cc';
import ActionEvent from './ActionEvent';
const { ccclass, property } = _decorator;

@ccclass('Player')
export class Player extends Component {
  @property
  jumpPower: number = 250;

  @property
  walkSpeed: number = 10;

  rigidBody: RigidBody2D;
  animation: Animation;
  audioSource: AudioSource;

  isJumping: boolean;
  animationType: 'walk' | 'idle' | 'jump' | 'climb';

  start() {
    this.isJumping = true;
    this.animationType = 'idle';
    this.rigidBody = this.node.getComponent(RigidBody2D);
    this.animation = this.node.getComponent(Animation);
    this.audioSource = this.node.getComponent(AudioSource);

    const colliders = this.getComponents(Collider2D);
    for (let collider of colliders) {
      if (collider.tag === 1) {
        collider.on(Contact2DType.BEGIN_CONTACT, () => {
          this.isJumping = false;
        }, this);
      }
    }
  }

  update(deltaTime: number) {
    let lv = this.rigidBody.linearVelocity;

    if (ActionEvent.isActionPressed('left')) {
      lv.x = -this.walkSpeed;
    } else if (ActionEvent.isActionPressed('right')) {
      lv.x = this.walkSpeed;
    } else {
      lv = new Vec2(0, lv.y);
    }

    if (ActionEvent.isActionJustPressed('jump') && !this.isJumping) {
      console.log('起跳', this.jumpPower)
      lv.y = this.jumpPower;
      this.animation.play('jump');
      this.animationType = 'jump';
      this.isJumping = true;
      this.audioSource.play();
    }

    this.rigidBody.linearVelocity = lv;

    if (lv.x !== 0) {
      this.node.setScale(new Vec3(Math.sign(lv.x), 1, 1));
    }

    if (lv.x !== 0 && !this.isJumping && this.animationType !== 'walk') {
      this.animation.play('walk');
      this.animationType = 'walk';
    }

    if (this.isJumping && this.animationType !== 'jump') {
      this.animation.play('jump');
    }

    if (lv.x === 0 && !this.isJumping && this.animationType !== 'idle') {
      this.animation.play('idle');
      this.animationType = 'idle';
    }
  }
}

