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

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

        public static TcpServer Instance => lazy.Value;

        private static LogHelper logHelper = LogHelper.Instance;

        public ServerState State
        {
            get => service.ServerState;
            private set => State = value;
        }

        TcpService service = new TcpService();

        public bool ServerStart(string ip, string port)
        {
            try
            {
                service.Connecting = (client, e) =>
                {
                    logHelper.Info($"客户端{client.IP}:{client.Port}正在连接");
                    return EasyTask.CompletedTask;
                };//有客户端正在连接
                service.Connected = (client, e) =>
                {
                    logHelper.Info($"客户端{client.IP}:{client.Port}成功连接");
                    return EasyTask.CompletedTask;
                };//有客户端成功连接
                service.Closing = (client, e) =>
                {
                    logHelper.Info($"客户端{client.IP}:{client.Port}正在断开连接");
                    return EasyTask.CompletedTask;
                };//有客户端正在断开连接，只有当主动断开时才有效。
                service.Closed = (client, e) =>
                {
                    logHelper.Info($"客户端{client.IP}:{client.Port}断开连接");
                    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();//此处可以添加插件
                    }));
                service.Start();//启动
                logHelper.Info("监听服务启动成功");
                return true;
            }
            catch (Exception ex)
            {
                logHelper.Error("监听服务启动失败! 错误代码" + ex.ToString());
                return false;
            }
        }

        public bool ServerStop()
        {
            try
            {
                service.Stop();
                logHelper.Info("监听服务关闭成功！");
                return true;
            }
            catch (Exception ex)
            {
                logHelper.Error("监听服务关闭失败! 错误代码" + ex.ToString());
                return false;
            }
        }

        public bool ServerDispose()
        {
            try
            {
                service.Dispose();
                logHelper.Info("监听服务释放成功！");
                return true;
            }
            catch (Exception ex)
            {
                logHelper.Error("监听服务释放失败! 错误代码" + ex.ToString());
                return false;
            }
        }

        private void BufferMemory(byte[] bytes)
        {
            byte[] identify = new byte[2] { bytes[1], bytes[2] };
            if (identify[0] == 0x30 && identify[1] == 0x31)
            {
                BufferAnalysis.HeartbeatSocket(bytes);
            }
            else if (identify[0] == 0x30 && identify[1] == 0x34)
            {
                BufferAnalysis.RFIDStatusSocket(bytes);
            }
            else if (identify[0] == 0x35 && identify[1] == 0x33)
            {
                BufferAnalysis.RFIDCodeSocket(bytes);
            }
        }

    }
}
