using HDLMonitorService.Helper;
using HDLMonitorService.UDP;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HDLMonitorService.ServiceMonitor
{
    public class ServerMonitor
    {
        /// <summary>
        /// 发送时间
        /// </summary>
        public static DateTime sendTime;
        /// <summary>
        /// 发送了多少次
        /// </summary>
        public static int ServerSendCount;
        /// <summary>
        /// 网络延迟次数
        /// </summary>
        public static int InternetDeleyCount;


        /// <summary>
        /// 监控数据转发服务
        /// </summary>
        public static void monitorServer()
        {
            new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    try
                    {
                        var sendBytes = new byte[29];
                        var groupNameBytes = Encoding.Default.GetBytes("HDLXX");
                        Array.Copy(groupNameBytes, 0, sendBytes, 9, groupNameBytes.Length);

                        sendBytes = Packet.SendBytes(sendBytes, 0x3011, 42, 0);

                        UDPServer.AsyncBeginSend(new Packet
                        {
                            Bytes = sendBytes,
                            RemoteEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ConfigurationManager.AppSettings["ServerIp"]), 9999)
                        });
                        sendTime = DateTime.Now;
                        ServerSendCount++;

                        //超过6次有问题
                        if (ServerSendCount == 6)
                        {
                            AlarmHp.ServiceAlarm("Server", "服务已经6次没有响应,请尽快检查!", ConfigurationManager.AppSettings["ServerIp"], "国内-旧服务器设备状态服务");
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHp.WriteLog("UDP服务异常", Newtonsoft.Json.JsonConvert.SerializeObject(ex));
                    }
                    Thread.Sleep(1000 * 10);
                }
            }))
            { IsBackground = true }.Start();
        }
    }
}