using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.Framework.Connection
{
    /// <summary>
    /// UDP终结点管理器扩展
    /// </summary>
    public static class UdpEndpointManagerExpand
    {
        /// <summary>
        /// 序列化设置
        /// </summary>
        private readonly static JsonSerializerSettings JSON_SERIALIZER_SETTINGS = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        };

        /// <summary>
        /// 发送字符串
        /// </summary>
        /// <param name="manager">UDP终结点管理器</param>
        /// <param name="msg">消息</param>
        /// <param name="encoding">字符编码方式</param>
        public static void SendString(this UdpEndpointManager manager, string msg, Encoding encoding)
        {
            byte[] buffer = encoding.GetBytes(msg);
            manager.Send(buffer);
        }

        /// <summary>
        /// 发送字符串(UDF-8编码)
        /// </summary>
        /// <param name="manager">UDP终结点管理器</param>
        /// <param name="msg">消息</param>
        public static void SendString(this UdpEndpointManager manager, string msg)
        {
            SendString(manager, msg, Encoding.UTF8);
        }

        /// <summary>
        /// 发送JSON字符串
        /// </summary>
        /// <param name="manager">UDP终结点管理器</param>
        /// <param name="obj">对象</param>
        /// <param name="encoding">字符编码方式</param>
        public static void SendJson(this UdpEndpointManager manager, object obj, Encoding encoding)
        {
            string msg = obj == null ? string.Empty : JsonConvert.SerializeObject(obj, JSON_SERIALIZER_SETTINGS);
            SendString(manager, msg, encoding);
        }

        /// <summary>
        /// 发送JSON字符串(UDF-8编码)
        /// </summary>
        /// <param name="manager">UDP终结点管理器</param>
        /// <param name="obj">对象</param>
        public static void SendJson(this UdpEndpointManager manager, object obj)
        {
            string msg = obj == null ? string.Empty : JsonConvert.SerializeObject(obj, JSON_SERIALIZER_SETTINGS);
            SendString(manager, msg, Encoding.UTF8);
        }
    }
}
