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

namespace VIZ.Framework.Connection
{
    /// <summary>
    /// 单条消息为JSON的处理器
    /// </summary>
    [ConnPackageProvider(ConnPackageProviderType.UDP)]
    public class ConnSingleJsonPackageProvider : IConnPackageProvider
    {
        public ConnSingleJsonPackageProvider()
        {
        }

        /// <summary>
        /// 日志
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(ConnSingleJsonPackageProvider));

        /// <summary>
        /// 数据编码
        /// </summary>
        public Encoding Encoding { get; set; } = Encoding.UTF8;

        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="package">数据包</param>
        public void Execute(ConnPackageInfo package)
        {
            string json = this.Encoding.GetString(package.Data, 0, package.DataSize);

            // 处理器处理消息
            ConnSingleJsonInfo info = new ConnSingleJsonInfo();
            info.LocalIP = package.LocalIP;
            info.LocalPort = package.LocalPort;
            info.RemoteIP = package.RemoteIP;
            info.RemotePort = package.RemotePort;
            info.Json = json;

            try
            {
                this.Execute(info);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            // 发送消息
            ConnSingleJsonMessage msg = new ConnSingleJsonMessage();
            msg.LocalIP = package.LocalIP;
            msg.LocalPort = package.LocalPort;
            msg.RemoteIP = package.RemoteIP;
            msg.RemotePort = package.RemotePort;
            msg.PortName = package.PortName;
            msg.Provider = this;
            msg.Json = json;

            try
            {
                ApplicationDomain.MessageManager.Send(msg);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="info">信息</param>
        protected virtual void Execute(ConnSingleJsonInfo info)
        {
            // noting to do.
        }
    }
}
