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

namespace MeterVision.Helper
{
    public class UdpSender
    {
        private static UdpSender _instance;
        private static readonly object _lock = new object();
        private UdpClient udpClient;
        private IPEndPoint remoteEndPoint;

        // 私有构造函数，防止外部实例化
        private UdpSender(string receiverIp, int receiverPort)
        {
            udpClient = new UdpClient();
            remoteEndPoint = new IPEndPoint(IPAddress.Parse(receiverIp), receiverPort);
        }

        // 获取单例实例
        public static UdpSender GetInstance(string receiverIp = "127.0.0.1", int receiverPort = 5000)
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new UdpSender(receiverIp, receiverPort);
                    }
                }
            }
            return _instance;
        }

        // 发送日志
        public void SendLog(string message)
        {
            try
            {
                byte[] data = Encoding.UTF8.GetBytes(message);
                udpClient.Send(data, data.Length, remoteEndPoint);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"日志发送失败: {ex.Message}");
            }
        }

        // 关闭 UDP 连接
        public void Close()
        {
            udpClient?.Close();
        }
    }
}
