using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Text;
using CacheManager.Core;
using Common;
using Dao;
using RCUHost.Protocols;

namespace RCUHost.Implement
{
    /// <summary>
    /// 解释域名的IP Receiver
    /// </summary>
    public class ExplainDomainIPReceiver : GenericReceiverBase, IExplainDomainIPReceiver
    {
        //private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HeartReceiver));

        public override void Process(ReceiverContext context)
        {
            //logger.Error("收到获取IP命令：" + Tools.ByteToString(context.Data));
            byte[] data = CreateDataPacket(context);
            Send(data, context.RemoteEndPoint);//解释域名IP，返回给rcu
        }

        private byte[] CreateDataPacket(ReceiverContext context)
        {
            SystemHeader systemHeader = CreateSystemHeader();

            var HostNumberOnly = context.SystemHeader.Value.HostNumber;
            System.Net.IPAddress ipAddr = System.Net.IPAddress.Parse("106.53.160.26");
            long code = HostNumberOnly.ToHotelCode();
            if (code != 1564)
            {
                ipAddr = Tools.GetIPByDomain("BoonliveNAS.synology.me");
            }
            byte[] ip = ipAddr.GetAddressBytes();
            //logger.Error("解释域名IP为：" + ipAddr.ToString());
            int size = StructConverter.SizeOf(systemHeader) + ip.Length + 2;
            systemHeader.FrameLength = (ushort)size;

            using (MemoryStream stream = new MemoryStream(size))
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    writer.Write(StructConverter.StructToBytes(systemHeader));
                    writer.Write(ip);
                    writer.Write(new byte[] { 0, 0 });
                    return stream.ToArray();
                }
            }
        }

        public override CommandType CommandType
        {
            get { return CommandType.ExplainDomainIP; }
        }
    }
}
