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} = cc._decorator;

@ccclass
export default class NetTester extends cc.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);
        }

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

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

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

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

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

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

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

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

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