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

@ccclass('GameSettleView')
export class GameSettleView extends Component {
    @property({type: SpriteFrame})
    genderBoySF: SpriteFrame = null;
    @property({type: SpriteFrame})
    genderGirlSF: SpriteFrame = null;
    @property({type: SpriteFrame})
    genderBoyFrameSF: SpriteFrame = null;
    @property({type: SpriteFrame})
    genderGirlFrameSF: SpriteFrame = null;

    start() {
        this.node.getChildByName("BtnRestart").on(Node.EventType.TOUCH_END, () => {
            director.loadScene("Game");
        });
        this._renderPlayerInfo(
            this.node.getChildByName("InfoSelf"),
            window.gm.state.myPlayerIndex
        );
        this._renderPlayerInfo(
            this.node.getChildByName("InfoOther"),
            (window.gm.state.myPlayerIndex + 1) % 2
        );
        let win = window.gm.state.authGameSystemState.winPlayerIndex === window.gm.state.myPlayerIndex;
        this.node.getChildByName("ImgWin").active = win;
        this.node.getChildByName("ImgLose").active = !win;
        if (win) window.gm.node.emit(GameEventEnum.GameWin);
        else window.gm.node.emit(GameEventEnum.GameLose);
    }

    private _renderPlayerInfo(node: Node, playerIndex: number) {
        let playerInfo = window.gm.state.matchPlayerInfos[playerIndex];
        let avatarSprite = node.getChildByPath("Mask/Avatar").getComponent(Sprite);
        let genderSprite = node.getChildByName("Gender").getComponent(Sprite);
        let genderFrameSprite = node.getChildByName("Frame").getComponent(Sprite);
        let nicknameLabel = node.getChildByName("Name").getComponent(Label);
        let hitCountLabel = node.getChildByName("HitCount").getComponent(Label);
        if (playerInfo.gender == 0) {
            genderSprite.spriteFrame = this.genderBoySF;
            genderFrameSprite.spriteFrame = this.genderBoyFrameSF;
        } else {
            genderSprite.spriteFrame = this.genderGirlSF;
            genderFrameSprite.spriteFrame = this.genderGirlFrameSF;
        }
        nicknameLabel.string = playerInfo.nickname;
        hitCountLabel.string = "打了" +
            window.gm.state.authGameSystemState.playerStates
                .find(v => v.index===playerIndex).accCount + "拳";
        Utils.LoadSpriteFrame(playerInfo.avatarUrl, 
            (spriteFrame: SpriteFrame) => avatarSprite.spriteFrame = spriteFrame);
    }
}


