using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using ZLog;

public class DemoSimple : MonoBehaviour
{
    //string m_Ip = "192.168.0.121";
    //string m_Ip = "8.134.36.175";
    //int m_Port = 9305;

    string m_Ip = "192.168.0.55";
    int m_Port = 9206;

    float reconnectTime = 0;

    private void Start()
    {
        // 设置日志的Level，屏蔽Socket的部分日志。设到2以下，查看所有日志
        Options.Instance.LogLevel = 3;
        //Log.Verbose = false;

        // 在主线程初始化ZLog
        Log.Debug("");

        // 连接服务器
        SimpleSocketManager.Connect(m_Ip, m_Port);

        // 发送心跳包消息的测试
        StartCoroutine(SendLoop());
    }

    private void Update()
    {
        if (SimpleSocketManager.Update() != ZSocket.ErrorCode.ERR_Success)
        {
            // 发生错误，重连处理
            if (Time.time > reconnectTime)
            {
                Debug.LogError($"Demo Reconnect ErrorCode: {SimpleSocketManager.ErrorCode}");
                SimpleSocketManager.Connect(m_Ip, m_Port);
                reconnectTime = Time.time + 1f;
            }
        }
    }

    private void OnDestroy()
    {
        // 断开与服务器的连接
        SimpleSocketManager.Disconnect();
    }

    IEnumerator SendLoop()
    {
        int i = 1;
        //while (i > 0)
        while (true)
        {
            i--;
            for (int j = 0; j < 1; ++j)
            {

                // 发送不需要回复的消息
                //Debug.Log($"Demo Send {SimpleSocketManager.ErrorCode}");
                //SimpleSocketManager.Send( "HEARTBEAT", @"{""ping"":true}");

                // 发送需要回复的RPC消息，结果通过回调获取
                Debug.Log($"Demo Rpc {SimpleSocketManager.ErrorCode}");
                SimpleSocketManager.Call("HEARTBEAT_REQ", @"{""ping"":true}", (err, msg) =>
                {
                    if (err != ZSocket.ErrorCode.ERR_Success)
                    {
                        Debug.LogError($"Demo Rpc Error: {err} {msg}");
                        return;
                    }

                    Debug.Log($"Demo Recv {msg}");
                });
            }

            yield return new WaitForSeconds(10f);
            //yield return new WaitForEndOfFrame();
        }
    }
}
