import { CoroutineV2 } from "../../CoroutineV2/CoroutineV2";
import { INetResponse } from "../Core/INetResponse";
import { NetConnector } from "../NetConnector";
import { NetManager } from "../NetManager";
import { Slot1_SpinRequestExample } from "./Slot1_SpinRequestExample";

const { ccclass, property } = console._decorator;

@ccclass
export default class NetTester extends console.Component {

    onConnectClicked() {
        CoroutineV2.StartCoroutine(this.ConnectAsync());
    }

    *ConnectAsync() {
        if (!NetManager.HasInit) {
            let conn = new NetConnector("192.168.7.165", 9005);
            conn.OnDataReceived.AddCallback(this.OnNetDataReceived, this);
            conn.OnDisconnected.AddCallback(this.OnNetDisconnected, this);
            conn.OnLoadUIMask.AddCallback(this.OnLoadUIMask, this);

            NetManager.Initialize(conn);
        }

        console.log("連線中...");
        yield NetManager.ConnectAsync(); // 同個connector要再次連線, 可以不用叫CasinoNetManager.Initialize(), 但要先叫CasinoNetManager.Disconnect()
        console.log(`連線狀態: ${NetManager.IsConnected}`);
    }

    onDisconnectClicked() {
        console.log("中斷連線中...");
        NetManager.Disconnect(); // 中斷連線
    }

    onSendMessageClicked1() {
        console.log("發送訊息(不使用協程)");
        let req = new Slot1_SpinRequestExample(401);
        req.Send();
        // CasinoNetManager.Send(req);
    }

    onSendMessageClicked2() {
        CoroutineV2.StartCoroutine(this.SendAsync());
    }

    *SendAsync() {
        console.log("發送訊息中(使用協程)...");
        let req = new Slot1_SpinRequestExample(399);
        yield req.SendAsync();
        // yield CasinoNetManager.SendAsync(req);

        let resp = req.Result;
        console.log(`發送協程完畢, Server回應: ${resp.Method}(${JSON.stringify(resp.Data)}), 狀態: ${resp.Status}`);
        // console.log(`使用介面資料: ${resp.Data.slot}`);
    }

    private OnNetDisconnected() {
        console.log("[事件] 收到連線中斷事件");
    }

    private OnNetDataReceived(resp: INetResponse<any>) {
        console.log(`[事件] 收到server呼叫: ${resp.Method}(${JSON.stringify(resp.Data)}), 狀態: ${resp.Status}`);
    }

    private OnLoadUIMask(value: boolean) {
        console.log(`[事件] LoadUIMask: ${value}`);
    }
}
