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

namespace Sln.Iot.Business
{
    /// <summary>
    /// TCP服务端
    /// </summary>
    public class TouchTcpServer
    {
        private static readonly Lazy<TouchTcpServer> lazy = new Lazy<TouchTcpServer>(() => new TouchTcpServer());

        public static TouchTcpServer Instance
        {
            get
            {
                return lazy.Value;
            }
        }

        /// <summary>
        /// 服务端启动
        /// </summary>
        public async void TcpServerStarted(string ipHost)
        {
            var service = new TcpService();
            service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接
            service.Connected = (client, e) => { return EasyTask.CompletedTask; };//有客户端成功连接
            service.Closing = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在断开连接，只有当主动断开时才有效。
            service.Closed = (client, e) => { return EasyTask.CompletedTask; };//有客户端断开连接

            #region Tcp服务器使用Received异步委托接收数据
            service.Received = async (client, e) =>
            {
                //从客户端收到信息
                var mes = e.Memory.Span.ToString(Encoding.UTF8);
                client.Logger.Info($"已从{client.Id}接收到信息：{mes}");
                TCPRFIDBinding.GetNewMessage?.Invoke(mes);
                //简单消除Task，当使用插件接收时，需要使用 await e.InvokeNext();来继续执行后续插件。
                await EasyTask.CompletedTask;
            };
            #endregion


            await service.SetupAsync(new TouchSocketConfig()//载入配置
                 .SetListenIPHosts($"tcp://{ipHost}")//可以同时监听多个地址
                 .ConfigureContainer(a =>//容器的配置
                 {
                     a.AddConsoleLogger();//添加一个控制台日志注入（注意：在maui中控制台日志不可用）
                 })
                 .ConfigurePlugins(a =>
                 {
                     //a.Add();//此处可以添加插件
                 }));

            await service.StartAsync();//启动
        }
    }
}
