import { _decorator, CCInteger, Component, Label, sp, Vec3, Node } from 'cc';
import { GameSystemInputType } from '../GameStruct';
const { ccclass, property } = _decorator;

@ccclass('Charactor')
export class Charactor extends Component {
    @property({type: CCInteger})
    playerIndex: number;
    basePosition: Vec3 = new Vec3();
    targetPosition: Vec3 = new Vec3();
    skeleton: sp.Skeleton;
    currentAnimationName: string;
    labelAccCount: Label = null;
    pointer: Node = null;

    start() {
        this.node.getPosition(this.basePosition);
        this.skeleton = this.getComponent(sp.Skeleton);
        //我方箭头显示并延时销毁
        if (window.gm.state.myPlayerIndex === this.playerIndex) {
            this.pointer = this.node.getChildByName("Pointer");
            this.pointer.active = true;
        }
        //计数标签
        this.labelAccCount = this.node.getChildByName("LabelAccCount").getComponent(Label);
    }

    playAnimation(name: string) {
        if (name === this.currentAnimationName) return;
        this.currentAnimationName = name;
        this.skeleton.setAnimation(0, name, true);
    }
    
    update(dt: number) {
        let ps = window.gm.state.gameSystemState.playerStates.find(v => v.index === this.playerIndex);
        if (ps) {
            this.targetPosition.set(this.basePosition).add3f(ps.moveX, 0, 0);
            this.node.setPosition(this.node.position.lerp(this.targetPosition, 20 * dt));
            if (ps.speedX / 100 >= 5) {
                this.playAnimation("Run3");
            } else if (ps.speedX / 100 >= 3) {
                this.playAnimation("Run2");
            } else if (ps.speedX > 0) {
                this.playAnimation("Run1");
            } else {
                this.playAnimation("idle");
            }
            this.labelAccCount.string = ps.accCount.toString();
        } else {
            this.playAnimation("idle");
        }
        //ReadyGo结束后要销毁箭头
        if (this.pointer && window.gm.state.gameSystemState.readyComplete) {
            this.pointer.destroy();
            this.pointer = null;
        }
    }

    inputAcc() {
        let accInput: PlayerAccInput = {
            type: GameSystemInputType.PlayerAcc,
            playerIndex: this.playerIndex,
        };
        window.gm.socketPlayer.cacheInputs(accInput);
    }
}


