using RTCommunicatorBase;
using TLVProtocal;
using UniversalNetFrame451.IO;

namespace AlarmInfoServerSim.Services
{
    public class InfoSendingService : IInfoSendingService, ITlvProvider, IDisposable
    {
        private readonly ISharedConfig _sharedConfig;
        private readonly ITlvCommunicatorServer _server;

        private bool _isConnected = false;
        private bool disposedValue;

        public InfoSendingService(ISharedConfig sharedConfig) 
        {
            _sharedConfig= sharedConfig;

            _server = TlvFactory.GetTlvServer();
            _server.Initialize(this);

            Open();
        }

        public event EventHandler<bool>? ConnectionStatusChanged;
        public event EventHandler<TcpConnection>? TcpConnectionChanged;

        public bool Open()
        {
            if (_sharedConfig.BasicInfo is not null)
            {
                return _server.Open(_sharedConfig.BasicInfo.RTServerAddress, _sharedConfig.BasicInfo.RTServerPort);
            }
            return false;
        }

        public bool Send(byte tag, ST_ALARM alarm)
        {
            if (_isConnected)
            {
                return _server.Send(tag, alarm);
            }
            return false;
        }

        public void Connected(TcpConnection connection)
        {
            _isConnected = true;
            ConnectionStatusChanged?.Invoke(null, _isConnected);
            TcpConnectionChanged?.Invoke(null, connection);
        }

        public void Disconnected(TcpConnection connection)
        {
            _isConnected = false;
            ConnectionStatusChanged?.Invoke(null, _isConnected);
            TcpConnectionChanged?.Invoke(null, connection);
        }

        public void Received(TlvData data)
        {
            throw new NotImplementedException();
        }

        public TlvData RequestReply(TlvData tlvData)
        {
            throw new NotImplementedException();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)
                    _server.Dispose();
                }

                // TODO: 释放未托管的资源(未托管的对象)并重写终结器
                // TODO: 将大型字段设置为 null
                disposedValue = true;
            }
        }

        // // TODO: 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器
        // ~SendInfoService()
        // {
        //     // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
        //     Dispose(disposing: false);
        // }

        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }
}
