using Modbus.Device;
using System;
using System.Net.Http;
using System.Net.Sockets;

namespace 自救器呼吸器综合检验仪.Data
{
    // 单例模式：全局唯一资源管理器
    public class ModbusResourceManager
    {
        // 私有构造函数：禁止外部new
        private ModbusResourceManager() { }

        // 唯一实例
        private static readonly Lazy<ModbusResourceManager> _instance = new Lazy<ModbusResourceManager>(() => new ModbusResourceManager());
        public static ModbusResourceManager Instance => _instance.Value;

        // 共享资源
        public TcpClient TcpClient { get; private set; }
        public IModbusMaster ModbusMaster { get; private set; }

        // 初始化资源（在程序启动时调用，如MainWindow加载时）
        public bool Init(string ip, int port)
        {
            try
            {
                // 先释放旧资源
                ReleaseResource();

                // 创建新连接
                TcpClient = new TcpClient();
                TcpClient.Connect(ip, port);
                ModbusMaster = ModbusIpMaster.CreateIp(TcpClient);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"资源初始化失败：{ex.Message}");
                ReleaseResource();
                return false;
            }
        }

        // 在 ModbusResourceManager 类中添加
        public void Dispose()
        {
            try
            {
                ModbusMaster?.Dispose();
                TcpClient?.Close();
            }
            catch
            {
                // 忽略清理时的异常
            }
        }

        // 释放资源（统一释放，避免重复关闭）
        public void ReleaseResource()
        {
            try
            {
                ModbusMaster?.Dispose();
                ModbusMaster = null;

                //if (TcpClient?.Connected ?? false)
                //{
                //    TcpClient.Close();
                //}
                TcpClient?.Dispose();
                TcpClient = null;
            }
            catch { }
        }
    }
}