using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Common;
using Domain;
using RCUHost.Protocols;
using Dao;
using CommonEntity;

namespace RCUHost.Implement
{
    /// <summary>
    /// 发送命令给rcu，获取密钥
    /// </summary>
    public class HostSecretReceiver : GenericReceiverBase, IHostSecretReceiver
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HostSecretReceiver));
        public IHostRepository HostRepository { get; set; }

        public void Send(Host host)
        {
            var data = CreateHostSecretPacket(host);
            Send(data, host.HostNumber, host.MAC);// host.IP, host.Port);
        }

        public byte[] CreateHostSecretPacket(Host host)
        {
            SystemHeader systemHeader = CreateSystemHeader();
            int size = StructConverter.SizeOf(systemHeader) + 2;
            systemHeader.FrameLength = (ushort)size;

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

        public override void Process(ReceiverContext context)
        {
            //base.Process(context);

            string HostNumberOnly = context.SystemHeader.Value.HostNumber.ToString();
            Host host = null;
            string Key = CacheKey.HostInfo_Key_HostNumber + "_" + HostNumberOnly;
            object obj = MemoryCacheHelper.Get(Key);
            if (obj != null)
            {
                host = obj as Host;
            }
            else
            {
                host = HostRepository.GetByHostNumber(context.SystemHeader.Value.HostNumber.ToString());
                MemoryCacheHelper.SlideSet(Key,host);
            }

            if (host != null)
            {
                try
                {
                    int offset = StructConverter.SizeOf(context.SystemHeader);
                    int length = context.Data.Length - offset - 2;
                    using (MemoryStream stream = new MemoryStream(context.Data, offset, length))
                    {
                        using (BinaryReader reader = new BinaryReader(stream))
                        {
                            reader.ReadBytes(4);//string hostVersion = String.Join(".", reader.ReadBytes(4));
                            reader.ReadBytes(6);//string mac = BitConverter.ToString(reader.ReadBytes(6));
                            string hostSecret = System.Text.Encoding.UTF8.GetString(reader.ReadBytes(32));
                            host.HostSecret = hostSecret;
                            HostRepository.Update(host);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(context.RemoteEndPoint.Address.ToString() + ":" + context.RemoteEndPoint.Port.ToString() + ":" + Tools.ByteToString(context.Data));
                    logger.Error("解析【" + host.HostNumber + "】客房主机密钥出错。", ex);
                }
            }
        }

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