using System;
using System.Collections.Generic;

namespace Plane.Communication
{
    /// <summary>
    /// 接收远程主机的 UDP 数据报并创建 <see cref="UdpServerConnection"/> 实例与其通信。
    /// </summary>
    public partial class UdpServerConnectionManager : ExceptionThrownEventSource, IDisposable
    {
        private static UdpServerConnectionManager _Instance = new UdpServerConnectionManager();

        private Dictionary<string, UdpServerConnection> _connections = new Dictionary<string, UdpServerConnection>();

        private bool _disposed;

        private bool _isReceiving;

        private bool _shouldReceive;

        public event EventHandler<ConnectionEstablishedEventArgs> ConnectionEstablished;

        public static UdpServerConnectionManager Instance { get { return _Instance; } }

        public void ClearConnections()
        {
            _connections.Clear();
        }

        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }
            StopReceiving();
            DisposeCore();
            _disposed = true;
        }

        private void RaiseConnectionEstablished(IConnection connection, string remoteAddress)
        {
            ConnectionEstablished?.Invoke(this, new ConnectionEstablishedEventArgs(connection, remoteAddress));
        }
    }
}
