using Common;
using Commonlib;
using LogCap.Common;
using LogCap.Entity;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.VisualBasic;
using MQTTnet;
using MQTTnet.Packets;
using MQTTnet.Protocol;
using NetMQ;
using NetMQ.Sockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using RestSharp.Authenticators.OAuth2;
using System.Collections;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace LogCap
{
    public class Program
    {

        public static MemoryCache Cache = new MemoryCache(new MemoryCacheOptions { });
        public static IMqttClient mqttClient { get; set; }

        public static DateTime CurrentTime { get; set; }

        public static int CurrentWangKaBianHao = 0;
        public static void Main(string[] args)
        {

            var NQQ = DateTime.Now.ToString("mmss");
            //var server = new ResponseSocket("@tcp://127.0.0.1:5556");
            //while (true)
            //{
            //    string frame = server.ReceiveFrameString();
            //    Console.WriteLine("Server received frame={0}", frame);
            //}
            //Console.ReadLine();
            //string SSS = Guid.NewGuid().ToString("N");
            //CurrentTime = DateTime.Now;

            //        var authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
            //"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2NGZjYjhjMS1jZDZjLTRkMTktOTc3My05YzkxYmZhNjQ2YWQiLCJpYXQiOjE3NDEyNDczNDAsImV4cCI6MTc0MTI1ODE0MCwic2NoZW1hIjoibnhnXzcwNzA1OTEzX2VhcXoiLCJ1c2VyIjoiYWYwNzg3YTQtMmM2NC00NWRiLWEzMjktNzg0ZGYwZWRjOGZjIiwiZGVmYXVsdF9wcm9wZXJ0eSI6IjA3MTY3M2IzLWQ4OTMtNDQwYi1iM2YwLTY0YTBkOTY0ZWIyOSIsInRvX3JlZnJlc2giOnRydWUsInR5cGUiOiJhY2Nlc3MiLCJpbml0X2Vwb2NoIjoxNzQxMjQ3MzQwLCJtZWRpdW1fY29kZSI6IldFQiJ9.4k2GE08J3MZQIgRKOx5dYmeL1vSnqDSC11MLpkDNjqQ", "token");
            //        var options = new RestClientOptions("https://api.fcs1cloud.com")
            //        {
            //            //Authenticator = authenticator

            //        };
            //        var client = new RestClient(options);

            //        //string str = Newtonsoft.Json.JsonConvert.SerializeObject(mm);
            //        //Console.WriteLine("发送MQTT的数据为：" + str);
            //        var request1 = new RestRequest("/api-secure/job/request", Method.Post);
            //        request1.AddHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2NGZjYjhjMS1jZDZjLTRkMTktOTc3My05YzkxYmZhNjQ2YWQiLCJpYXQiOjE3NDEyNDczNDAsImV4cCI6MTc0MTI1ODE0MCwic2NoZW1hIjoibnhnXzcwNzA1OTEzX2VhcXoiLCJ1c2VyIjoiYWYwNzg3YTQtMmM2NC00NWRiLWEzMjktNzg0ZGYwZWRjOGZjIiwiZGVmYXVsdF9wcm9wZXJ0eSI6IjA3MTY3M2IzLWQ4OTMtNDQwYi1iM2YwLTY0YTBkOTY0ZWIyOSIsInRvX3JlZnJlc2giOnRydWUsInR5cGUiOiJhY2Nlc3MiLCJpbml0X2Vwb2NoIjoxNzQxMjQ3MzQwLCJtZWRpdW1fY29kZSI6IldFQiJ9.4k2GE08J3MZQIgRKOx5dYmeL1vSnqDSC11MLpkDNjqQ");

            //        //注意方法是POST
            //        //两个参数名字必须是 topic 和payload ，区分大小写的
            //        //Console.WriteLine("Topic: " + debug_log_report_mqtt_topic);


            var list = CSRedisCacheHelper.Get<List<Monitor_Host>>(CacheKey.Key);
            Cache.Set<List<Monitor_Host>>(CacheKey.Key, list);

            //端点监控
            var QQQ = CSRedisCacheHelper.Get<List<MonitorEndPoint>>(CacheKey.MonitorEndPointList);
            Cache.Set<List<MonitorEndPoint>>(CacheKey.MonitorEndPointList, QQQ);

            _ = Start_MqttClient();
            System.Timers.Timer timer = new System.Timers.Timer();

            timer.Elapsed += Timer_Elapsed;
            timer.Interval = 10000;
            timer.Enabled = true;
            timer.Start();

            System.Timers.Timer timer1 = new System.Timers.Timer();
            timer1.Elapsed += Timer1_Elapsed;

            timer1.Interval = 60000;
            timer1.Enabled = true;
            timer1.Start();

            PubRepository.GetDeviceList();

            Console.WriteLine("选择你要监控的网卡");
            //string whitchone = Console.ReadLine();

            string whitchone = "3";
            int.TryParse(whitchone, out CurrentWangKaBianHao);


            PubRepository.StartMonitor(CurrentWangKaBianHao);
            Console.WriteLine("正在监控中");
            Console.WriteLine("……………………………………………………………………………………………………………………………………………………………………………………");
            Console.WriteLine("按回车键就结束");
            string? nnn = Console.ReadLine();
            PubRepository.StopMonitor();
            timer.Dispose();
        }

        private static async void Timer1_Elapsed(object? sender, ElapsedEventArgs e)
        {
            try
            {
                Console.WriteLine("现在的数量是："+LogExecute.TotalCountGlobal);
                long lla= Interlocked.Read(ref LogExecute.TotalCountGlobal);
                CSRedisCacheHelper.Publish("wireshark-cap-udp-totalcount",lla.ToString());
                Interlocked.Exchange(ref LogExecute.TotalCountGlobal, 0);
            }
            catch (Exception)
            {

            }
        }

        private static async Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        {
            Console.WriteLine("断线重连了");
            await Task.Delay(3000);
            await Start_MqttClient();
        }

        private static Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            try
            {
                var str = arg.ApplicationMessage.Payload;

                string nnn = Encoding.UTF8.GetString(str);
                Monitor_Host? vvv = JsonConvert.DeserializeObject<Monitor_Host>(nnn);

                if (vvv != null)
                {
                    string Key = string.Format("{0}_{1}", CacheKey.RoomIP_Port_Prefix, vvv.Key_HostNumber);

                    var takeMM = Program.Cache.Get<MonitorRedis>(Key);
                    if (takeMM != null)
                    {
                        string IP = takeMM.WWW_IP;
                        int Port = takeMM.WWW_Port;
                        string KeyHeartBeat = string.Format("{0}_{1}_{2}", CacheKey.RoomIP_Port_Prefix, IP, Port);
                        Program.Cache.Remove(KeyHeartBeat);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("MqttClient_ApplicationMessageReceivedAsync: " + ex.Message);
            }
            return Task.CompletedTask;
        }

        private static async void Timer_Elapsed(object? sender, ElapsedEventArgs e)
        {

            try
            {
                Console.WriteLine("定时任务");
                var list = CSRedisCacheHelper.Get<List<Monitor_Host>>(CacheKey.Key);
                Cache.Set<List<Monitor_Host>>(CacheKey.Key, list);
                if (list != null && list.Count != 0)
                {
                    TimeSpan span = DateTime.Now - Program.CurrentTime;
                    if (span.TotalSeconds >= 35)
                    {
                        PubRepository.StopMonitor();
                        PubRepository.StartMonitor(CurrentWangKaBianHao);
                    }
                }

                //端点监控
                var QQQ = CSRedisCacheHelper.Get<List<MonitorEndPoint>>(CacheKey.MonitorEndPointList);
                Cache.Set<List<MonitorEndPoint>>(CacheKey.MonitorEndPointList, QQQ);

                var hhh = await mqttClient.PublishStringAsync("/blw/heart/logcap", "heartbeat");
                if (hhh.IsSuccess == false)
                {
                    await Start_MqttClient();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("timer_elapsed: " + ex.Message);
            }
        }

        async public static Task Start_MqttClient()
        {

            try
            {
                var mqttFactory = new MqttClientFactory();

                string? ip = ReadConfig.Instance.MQTT_ServerIP;
                int? port = ReadConfig.Instance.MQTT_ServerPort;
                string? username = ReadConfig.Instance.MQTT_User;
                string? pwd = ReadConfig.Instance.MQTT_PassWord;

                //long lid = Tools.ToUnixTimestampBySeconds(DateTime.Now);

                string lid = Guid.NewGuid().ToString("N");

                string ID = $"logmonitor_{lid}";
                mqttClient = mqttFactory.CreateMqttClient();
                var mqttClientOptions = new MqttClientOptionsBuilder()
                    .WithClientId(ID)
                    .WithTcpServer(ip, port)
                    .WithCredentials(username, pwd)
                    .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V500)
                    .Build();

                mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
                mqttClient.DisconnectedAsync += MqttClient_DisconnectedAsync;
                await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);

                //var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
                //    .WithTopicFilter("blw/logmonitor/delete/report")
                //    .Build();

                //var nnn = new MqttTopicFilterBuilder().WithTopic("blw/logmonitor/delete/report");

                var subscribeOptions = new MqttClientSubscribeOptions();
                var topicFilter = new MqttTopicFilter
                {
                    Topic = "blw/logmonitor/delete/report"
                };
                subscribeOptions.TopicFilters.Add(topicFilter);
                await mqttClient.SubscribeAsync(subscribeOptions, CancellationToken.None);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Start_MqttClient: " + ex.Message);
            }
        }
    }

    public class GGH
    {
        public List<string> location_uuid { get; set; }
        public List<GGJ> service_items { get; set; }
        public string remark { get; set; }
        public string assigned_to { get; set; }
        public int user_type { get; set; }
    }
    public class GGJ
    {
        public string item_uuid { get; set; }
        public int quantity { get; set; }
    }
}
