using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MeterVision.Helper
{
    public class UdpLoggerSender
    {
        private static UdpLoggerSender _instance;
        private static readonly object _lock = new object();

        private readonly ConcurrentQueue<string> _logQueue = new ConcurrentQueue<string>();  // 日志队列
        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
        private readonly Task _logTask;
        private readonly UdpClient _udpClient;
        private readonly IPEndPoint _remoteEndPoint;

        private UdpLoggerSender(string ip, int port)
        {
            // 初始化 UDP 发送端
            _udpClient = new UdpClient();
            _remoteEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);

            // 启动后台任务，异步处理日志队列
            _logTask = Task.Run(ProcessLogQueue, _cts.Token);
        }

        public static UdpLoggerSender GetInstance(string ip = "127.0.0.1", int port = 5000)
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                        _instance = new UdpLoggerSender(ip, port);
                }
            }
            return _instance;
        }

        /// <summary>
        /// 添加日志到队列（调用频繁，不会创建新线程）
        /// </summary>
        public void EnqueueLog(string message)
        {
            _logQueue.Enqueue(message);
        }

        /// <summary>
        /// 后台任务，循环处理日志队列，异步发送日志
        /// </summary>
        private async Task ProcessLogQueue()
        {
            while (!_cts.Token.IsCancellationRequested)
            {
                if (_logQueue.TryDequeue(out string logMessage))
                {
                    try
                    {
                        await SendLogAsync(logMessage);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"日志发送失败: {ex.Message}");
                    }
                }
                else
                {
                    // 队列为空时稍作等待，避免 CPU 100%
                    await Task.Delay(10);
                }
            }
        }

        /// <summary>
        /// 通过 UDP 发送日志
        /// </summary>
        private async Task SendLogAsync(string message)
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            await _udpClient.SendAsync(data, data.Length, _remoteEndPoint);
            //Debug.WriteLine($"UDP 发送: {message}");
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Stop()
        {
            _cts.Cancel();
            _logTask.Wait();
            _udpClient.Close();
        }
        //----------------------------------------------------------
    }
}
