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

namespace WCS.BLL.Tool
{
    internal class HeartbeatAndReceivePlugin : PluginBase, ITcpConnectedPlugin<ITcpClientBase>, ITcpDisconnectedPlugin<ITcpClientBase>, ITcpReceivedPlugin<ITcpClientBase>
    {
        private readonly int m_timeTick;
        private readonly ILog logger;

        [DependencyInject("20000")]
        public HeartbeatAndReceivePlugin(int timeTick, ILog logger)
        {
            this.m_timeTick = 20000;
            this.logger = logger;
        }


        public async Task OnTcpConnected(ITcpClientBase client, ConnectedEventArgs e)
        {
            if (client is ISocketClient)
            {
                return;//此处可判断，如果为服务器，则不用使用心跳。
            }

            if (client.GetValue(DependencyExtensions.HeartbeatTimerProperty) is Timer timer)
            {
                timer.Dispose();
            }

            client.SetValue(DependencyExtensions.HeartbeatTimerProperty, new Timer((o) =>
            {
                client.Ping();
            }, null, 0, this.m_timeTick));
            await e.InvokeNext();
        }

        public async Task OnTcpDisconnected(ITcpClientBase client, DisconnectEventArgs e)
        {
            if (client.GetValue(DependencyExtensions.HeartbeatTimerProperty) is Timer timer)
            {
                timer.Dispose();
                client.SetValue(DependencyExtensions.HeartbeatTimerProperty, null);
            }

            await e.InvokeNext();
        }

        public async Task OnTcpReceived(ITcpClientBase client, ReceivedDataEventArgs e)
        {
            if (e.RequestInfo is MyRequestInfo myRequest)
            {
                this.logger.Info(myRequest.ToString());
                if (myRequest.DataType == DataType.Ping)
                {
                    client.Pong();
                }
            }
            await e.InvokeNext();
        }
    }
}
