using System;
using Modbus.Device;
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;
            }
        }

        public void Dispose()
        {
            ReleaseResource();
        }

        // 释放资源（统一释放，避免重复关闭）
        public void ReleaseResource()
        {
            try
            {
                // 先释放 ModbusMaster
                if (ModbusMaster != null)
                {
                    try
                    {
                        ModbusMaster.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"释放ModbusMaster失败：{ex.Message}");
                    }
                    finally
                    {
                        ModbusMaster = null;
                    }
                }

                // 再释放 TcpClient
                if (TcpClient != null)
                {
                    try
                    {
                        if (TcpClient.Connected)
                        {
                            TcpClient.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"关闭TcpClient失败：{ex.Message}");
                    }

                    try
                    {
                        TcpClient.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"释放TcpClient失败：{ex.Message}");
                    }
                    finally
                    {
                        TcpClient = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"资源释放异常：{ex.Message}");
            }
        }
    }
}