using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using BestHTTP.WebSocket;
using Cysharp.Threading.Tasks;
using DotRecast.Core.Collections;
using Google.Protobuf;
using Plugins.JNGame.Network.Entity;
using Plugins.JNGame.Network.Util;
using Plugins.JNGame.Util;
using TouchSocket.Core;
using TouchSocket.Http.WebSockets;
using TouchSocket.Sockets;
using UnityEngine;

namespace Plugins.JNGame.Network
{
    public abstract class JNSocket : JNClientBase
    {
        
        private WebSocketClient client;

        public override async Task OnInit()
        {
            await StartConnect();
        }
        
        public async Task StartConnect()
        {
            
            client = new WebSocketClient();
            
            await client.SetupAsync(new TouchSocketConfig()
                .SetRemoteIPHost(await this.GetUrl())
                .ConfigurePlugins(a =>
                {
                    a.UseReconnection(-1, true, 1000);   //如需永远尝试连接,tryCount设置为-1即可。
                })
                .ConfigureContainer(a =>
                {
                    a.AddConsoleLogger();
                }));
            client.Received += OnReceived;
            
            client.Connect();
            Debug.Log($"[JNSocket]连接WebSocket成功");
            
        }

        public override void OnClose()
        {
            client.Close();
            client.Dispose();
            Debug.Log($"[JNTCPClient] 关闭对象");
            base.OnClose();
        }
        
        private Task OnReceived(WebSocketClient webSocketClient, WSDataFrameEventArgs e)
        {
            if (e.DataFrame.Opcode == WSDataType.Binary && e.DataFrame.FIN)
            {
                Dispatch(NDataUtil.Parse(e.DataFrame.PayloadData));
            }
            return Task.CompletedTask;
        }


        protected abstract UniTask<string> GetUrl();
        
        public override void SendBytes(byte[] data)
        {
            client.SendAsync(data);
        }
        
    }
}