import { _decorator, Component, Label, Node, Sprite, SpriteFrame } from 'cc';
import { Utils } from '../../Common/Utils';
const { ccclass, property } = _decorator;

@ccclass('GameModeView')
export class GameModeView extends Component {
    private otherAvatar: Node;
    private labelDistanceToEnd: Label;

    protected start(): void {
        //加速按钮
        this.node.on(Node.EventType.TOUCH_START, () => {
            window.gm.mode.getCharactor(window.gm.state.myPlayerIndex).inputAcc();
        });
        //他人去向
        this.otherAvatar = this.node.getChildByName("OtherAvatar");
        let playerInfo = window.gm.state.matchPlayerInfos[(window.gm.state.myPlayerIndex + 1) % 2];
        let avatarSprite = this.otherAvatar.getChildByPath("Avatar/Sprite").getComponent(Sprite);
        if (playerInfo) {
            Utils.LoadSpriteFrame(playerInfo.avatarUrl, 
                (spriteFrame: SpriteFrame) => avatarSprite.spriteFrame = spriteFrame);
        }
        this.otherAvatar.active = false;
        //终点距离
        this.labelDistanceToEnd = this.node.getChildByName("LabelDistanceToEnd").getComponent(Label);
    }

    protected update(dt: number): void {
        //更新显示他人去向
        let ps = window.gm.state.gameSystemState.playerStates.find(v => v.index === window.gm.state.myPlayerIndex);
        let ops = window.gm.state.gameSystemState.playerStates.find(v => v.index !== window.gm.state.myPlayerIndex);
        if (ps && ops) {
            let dist = ops.moveX - ps.moveX;
            let absDist = Math.abs(dist);
            if (absDist > 380) {
                this.otherAvatar.position.set(
                    Math.abs(this.otherAvatar.position.x) * (dist > 0 ? 1 : -1),
                    this.otherAvatar.position.y
                );
                this.otherAvatar.setPosition(this.otherAvatar.position);
                this.otherAvatar.getChildByName("ArrowA").active = dist < 0;
                this.otherAvatar.getChildByName("ArrowB").active = dist > 0;
                this.otherAvatar.getChildByName("LabelDistance").getComponent(Label).string = (absDist / window.gm.config.gameLenDivRealLen).toFixed(2) + "米"
                this.otherAvatar.active = true;
            } else {
                this.otherAvatar.active = false;
            }
        }
        //更新终点距离
        if (ps) {
            let dist = window.gm.config.endPointDistance - ps.moveX
            if (dist < 0) dist = 0;
            this.labelDistanceToEnd.string = "距离终点" + (dist / window.gm.config.gameLenDivRealLen).toFixed(2) + "米"
        }
    }
}


