using System;
using System.Net;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using Plugins.JNGame.Network;
using Plugins.JNGame.Network.Action;
using Plugins.JNGame.Network.Entity;
using Plugins.JNGame.Network.Util;
using TouchSocket.Core;
using TouchSocket.Sockets;
using UnityEngine;
using NotImplementedException = System.NotImplementedException;

namespace JNGame.Network
{
    public class JNTCPClient : JNClientBase
    {
        
        private TcpClient tcpClient;
        public bool IsOpen => tcpClient is not null && tcpClient.Online;
        
        
        public override async Task OnInit()
        {
            tcpClient = new TcpClient();
            await tcpClient.SetupAsync(
                new TouchSocketConfig()
                    .ConfigurePlugins(a =>
                    {
                        a.UseReconnection(-1, true, 1000);   //如需永远尝试连接,tryCount设置为-1即可。
                    })
                    .SetTcpDataHandlingAdapter(() => new FixedHeaderPackageAdapter())
            );
            tcpClient.Connecting = OnConnecting;
            tcpClient.Connected = OnConnected;//成功连接到服务器
            tcpClient.Disconnected = OnDisconnected;//从服务器断开连接,当连接不成功时不会触发。
            tcpClient.Received = OnReceived;

            await tcpClient.ConnectAsync(await GetEndPoint());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private async Task OnConnecting(ITcpClient client, ConnectingEventArgs e)
        {
            Debug.Log($"[JNTCPClient] 开始连接服务器 {await GetEndPoint()}");
        }


        /// <summary>
        /// 成功连接到服务器
        /// </summary>
        /// <param name="client"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private Task OnConnected(ITcpClient client, ConnectedEventArgs e)
        {
            Debug.Log($"[JNTCPClient] 服务器连接成功");
            Dispatch(new JNetParam(_id++,(int)NActionEnum.LocalClientConnect));
            return Task.CompletedTask;
        }

        /// <summary>
        /// 从服务器断开连接,当连接不成功时不会触发。
        /// </summary>
        /// <param name="client"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private Task OnDisconnected(ITcpClientBase client, DisconnectEventArgs e)
        {
            Debug.Log($"[JNTCPClient] 服务器断开");
            Dispatch(new JNetParam(_id++,(int)NActionEnum.LocalClientDisconnect));
            return Task.CompletedTask;
        }
        
        /// <summary>
        /// 接收到消息
        /// </summary>
        /// <param name="client"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private Task OnReceived(TcpClient client, ReceivedDataEventArgs e)
        {
            byte[] data = new byte[e.ByteBlock.Len];
            Array.Copy(e.ByteBlock.Buffer,data, data.Length);
            var param = NDataUtil.Parse(data);
            Dispatch(param);
            return Task.CompletedTask;
        }


        public override void SendBytes(byte[] data)
        {
            if (IsOpen)
            {
                tcpClient.Send(data);
            }
        }


        public override void OnClose()
        {
            tcpClient.Close();
            tcpClient.Dispose();
            Debug.Log($"[JNTCPClient] 关闭对象");
            base.OnClose();
        }

        protected virtual async UniTask<string> GetEndPoint()
        {
            await UniTask.NextFrame();
            return "127.0.0.1:9001";
        }
        
        
    }
}