using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace NDSD_TouchSocket
{
    public class TcpServer
    {
        private static readonly Lazy<TcpServer> lazy = new Lazy<TcpServer>(() => new TcpServer());

        public static TcpServer Instance => lazy.Value;

        string ClientIP;
        string ClientPort;

        TcpService service;

        public bool ServerOpen(string ip, string port)
        {

            service = new TcpService();

            try
            {
                service.Connecting = (client, e) =>
                {
                    Console.WriteLine(client.IP + " 正在连接");
                    return EasyTask.CompletedTask;
                };//有客户端正在连接
                service.Connected = (client, e) =>
                {
                    Console.WriteLine(client.IP + " 成功连接");
                    service.ResetIdAsync(client.Id, client.IP);
                    this.ClientIP = client.IP;
                    this.ClientPort = client.Port.ToString();
                    return EasyTask.CompletedTask;
                };//有客户端成功连接
                service.Closing = (client, e) =>
                {
                    Console.WriteLine(client.IP + " 正在断开连接");
                    return EasyTask.CompletedTask;
                };//有客户端正在断开连接，只有当主动断开时才有效。
                service.Closed = (client, e) =>
                {
                    Console.WriteLine(client.IP + " 断开连接");
                    return EasyTask.CompletedTask;
                };//有客户端断开连接
                service.Received = (client, e) =>
                {
                    ////从客户端收到信息
                    //var mes = Encoding.ASCII.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意：数据长度是byteBlock.Len
                    //logHelper.Info($"已从{client.IP}:{client.Port}接收到信息：{mes}");

                    //BufferMemory(BufferAnalysis.SplitByteArray(e.ByteBlock.Span.ToArray(), 0, e.ByteBlock.Length));

                    return EasyTask.CompletedTask;
                };

                service.Setup(new TouchSocketConfig()//载入配置
                    .SetListenOptions(option =>
                    {
                        option.Add(new TcpListenOption()
                        {
                            IpHost = ip + ":" + port,
                            Name = "Server",//名称用于区分监听
                            ServiceSslOption = null,//可以针对当前监听，单独启用ssl加密
                            Adapter = () => new NormalDataHandlingAdapter(),//可以单独对当前地址监听，配置适配器
                                                                            //还有其他可配置项，都是单独对当前地址有效。
                        });
                    })
                    .ConfigureContainer(a =>//容器的配置顺序应该在最前面
                    {
                        a.AddConsoleLogger();//添加一个控制台日志注入（注意：在maui中控制台日志不可用）
                    })
                    .ConfigurePlugins(a =>
                    {
                        //a.Add();//此处可以添加插件
                    }));
                try
                {
                    service.Start();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public void SendMessage(byte[] bytes)
        {
            //尝试性获取
            if (service.TryGetClient(ClientIP, out var sessionClient))
            {
                sessionClient.SendAsync(bytes);
            }
            return;
        }

        public bool Isopen()
        {
            if (service.ServerState == ServerState.None)
            {
                return false;
            }
            return true;
        }

        public bool Isstart()
        {
            if (service.ServerState == ServerState.Stopped)
            {
                return false;
            }
            return true;
        }

        public bool ServerStart()
        {
            try
            {
                service.Start();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public bool ServerStop()
        {
            try
            {
                service.Stop();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public bool ServerDispose()
        {
            try
            {
                service.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public bool ServerRestart(string ip, string port)
        {
            try
            {
                service.Stop();
                service.Dispose();
                ServerOpen(ip, port);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        //private void BufferMemory(byte[] bytes)
        //{
        //    if (bytes[4] == 0x00 && bytes[5] == 0xB9)
        //    {
        //        BufferAnalysis.JudgeSingle(false);
        //    }
        //    else if (bytes[4] == 0xFF && bytes[5] == 0xF9)
        //    {
        //        BufferAnalysis.JudgeSingle(true);
        //    }
        //}

    }
}
