import { director, game } from "cc";
import { tgxUIAlert, tgxUIController, tgx_class } from "../../core_tgx/tgx";
import { GameUILayers } from "../../scripts/GameUILayers";
import { ModuleDef } from "../../scripts/ModuleDef";
import { SubGameMgr } from "../../module_basic/scripts/SubGameMgr";
import { UserMgr } from "../../module_basic/scripts/UserMgr";
import { Layout_SearchingRival } from "./Layout_SearchingRival";

@tgx_class(ModuleDef.Arean)
export class UI_SearchingRival extends tgxUIController {

    public params :any
    constructor() {
        super('ui_searching_rival/ui_searching_rival', GameUILayers.POPUP, Layout_SearchingRival);
    }


    private _startTime = Date.now();
    private _state = '';
    protected onCreated(): void {
        let layout = this.layout as Layout_SearchingRival;
        this.onButtonEvent(layout.btnCancel, async () => {
            if(this._state == 'matching'){
                let ret = await UserMgr.inst.rpc_QuickPlayCancel();
                if (ret.isSucc) {
                    this._state = 'cancelled';
                    this.close();
                }
            }
            else{
                this._state = 'cancelled';
                this.close();
            }
            
        });
    }

    protected onUpdate(dt: number): void {
        let layout = this.layout as Layout_SearchingRival;
        let elapsedTime = Math.floor((Date.now() - this._startTime) / 1000);
        if (elapsedTime < 60) {
            layout.lblTime.string = elapsedTime + '秒';
        }
        else {
            let s = elapsedTime % 60;
            let m = Math.floor(elapsedTime / 60);
            layout.lblTime.string = m + '分' + s + '秒';
        }
    }

    async startMatch(type: string,fun :Function) {
        if(this._state){
            return;
        }
        this._state = 'matching';
        let ret = await UserMgr.inst.rpc_QuickPlay(type);
        console.log('startMatch', ret);
        if (!ret.isSucc) {
            tgxUIAlert.show('未找到适合的对手');
        }
        else {
            let params = ret.res;
            this.params = params;
            if(!ret.res.isWaiting){
                this.close();
                return await SubGameMgr.inst.enterSubGame(params,UserMgr.inst.uid);
            }else{
                 if(fun){
                    fun(params);
                 }
            }
        }
    }
}