using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using log4net;
using VIZ.Framework.Domain;

namespace VIZ.Framework.Connection
{
    /// <summary>
    /// UDP网络终结点管理器
    /// </summary>
    public class UdpEndpointManager
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(UdpEndpointManager));

        /// <summary>
        /// 网络终结点键<see cref="UdpEndpointKeys"/>
        /// </summary>
        public string Key { get; private set; }

        /// <summary>
        /// 监听IP
        /// </summary>
        public string IP { get; private set; }

        /// <summary>
        /// 监听端口
        /// </summary>
        public int Port { get; private set; }

        /// <summary>
        /// UDP客户端
        /// </summary>
        public UdpClient UdpClient { get; internal set; }

        /// <summary>
        /// UDP连接
        /// </summary>
        public UdpConnection UdpConnection { get; internal set; }

        /// <summary>
        /// UDP终结点管理器
        /// </summary>
        /// <param name="key">网络终结点键></param>
        /// <param name="ip">IP地址</param>
        /// <param name="port">端口</param>
        public UdpEndpointManager(string key, string ip, int port)
        {
            this.Key = key;
            this.IP = ip;
            this.Port = port;
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="buffer">数据</param>
        public void Send(byte[] buffer)
        {
            this.UdpClient.Send(buffer, buffer.Length, this.IP, this.Port);

            ConnSendMessage msg = new ConnSendMessage();
            msg.LocalIP = this.UdpConnection.IP;
            msg.LocalPort = this.UdpConnection.Port;
            msg.RemoteIP = this.IP;
            msg.RemotePort = this.Port;
            msg.Buffer = buffer;

            ApplicationDomain.MessageManager.Send(msg);
        }
    }
}
