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

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

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

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

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