import { _decorator, Component} from 'cc';
import { SocketPlayer } from '../SocketPlayer';
import { GameEventEnum } from '../GameStruct';
import MatchPanel from '../../../Packages/MatchPanel/MatchPanel';
import WebViewListener from '../../ThirdParty/BiBeng/WebViewListener';
const { ccclass, property } = _decorator;

@ccclass('GameMatchView')
export class GameMatchView extends Component {

    protected onLoad(): void {
        window.gm.node.once(GameEventEnum.MatchEnd, () => {
            for (let i = 0; i < window.gm.state.matchPlayerInfos.length; i++) {
                if (i === window.gm.state.myPlayerIndex) continue;
                this._renderOther(window.gm.state.matchPlayerInfos[i]);
                break;
            }
            //请求开始帧同步
            this.scheduleOnce(() => {
                window.gm.socketPlayer.startFrameSync();
            }, window.gm.config.debugQuicklyStartGame ? 0 : 3.5);
        });
        window.gm.node.once(GameEventEnum.GameStart, () => {
            this.node.destroy();
        });
    }

    protected start(): void {
        if (WebViewListener.Init()) {
            window.gm.node.once(GameEventEnum.UniAppGameInit, (arg0) => {
                BuiltinMatchInfos.myPlayerInfo = arg0;
                this._startMatching();
            });
        } else {
            this._startMatching();
        }
    }

    private _startMatching() {
        this._renderSelf();
        window.gm.socketPlayer = new SocketPlayer();
    }

    private _renderSelf() {
        let playerInfo = BuiltinMatchInfos.myPlayerInfo;
        MatchPanel.Instance.renderMyInfo(
            playerInfo.nickname, 
            playerInfo.gender == 0 ? MatchPanel.GENDER_BOY : MatchPanel.GENDER_GIRL,
            playerInfo.avatarUrl
        );
    }

    private _renderOther(playerInfo: MatchPlayerInfo) {
        MatchPanel.Instance.renderOtherInfo(
            playerInfo.nickname, 
            playerInfo.gender == 0 ? MatchPanel.GENDER_BOY : MatchPanel.GENDER_GIRL,
            playerInfo.avatarUrl
        );
    }
}

/**内置匹配信息（默认玩家和多个AI） */
export class BuiltinMatchInfos {
    public static myPlayerInfo: MatchPlayerInfo = {
        nickname: "光头",
        gender: 0,
        avatarUrl: "headphotos/master"
    };
    public static aiPlayerInfos: MatchPlayerInfo[] = [
        {
            nickname: "大佬啊",
            gender: 0,
            avatarUrl: "headphotos/0"
        },
        {
            nickname: "天天睡懒觉",
            gender: 1,
            avatarUrl: "headphotos/1"
        },
        {
            nickname: "这也太奢侈了吧",
            gender: 0,
            avatarUrl: "headphotos/2"
        },
        {
            nickname: "我要起飞咯",
            gender: 1,
            avatarUrl: "headphotos/3"
        },
        {
            nickname: "工作不如睡觉",
            gender: 0,
            avatarUrl: "headphotos/4"
        },
    ];
}
