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

namespace RCUHost.Implement
{
    public class AuthorizationReceiver : GenericReceiverBase, IAuthorizationReceiver
    {
        public IHostRepository HostRepository { get; set; }

        public void AccreditForHost(IList<Host> hostList, DateTime expires)
        {
            ushort days = Convert.ToUInt16((DateTime.Parse(expires.ToString("yyyy-MM-dd " + DateTime.Now.ToLongTimeString())) - DateTime.Now).TotalDays);

            foreach (var host in hostList)
            {
                //Send(CreateDataPacket(days), host.IP, host.Port);
            }
        }

        private byte[] CreateDataPacket(ushort days)
        {
            //SystemHeader systemHeader = CreateSystemHeader();

            //using (MemoryStream stream = new MemoryStream())
            //{
            //    var headerLen = StructConverter.SizeOf(systemHeader);

            //    stream.Seek(headerLen, SeekOrigin.Begin);

            //    stream.Write(BitConverter.GetBytes(days), 0, 2);
            //    stream.Write(new byte[] { 0, 0 }, 0, 2);

            //    var systemHeaderData = StructConverter.StructToBytes(systemHeader);


            //    stream.Seek(0, SeekOrigin.Begin);
            //    stream.Write(systemHeaderData, 0, systemHeaderData.Length);

            //    return stream.ToArray();
            //}

            byte[] day = BitConverter.GetBytes(days);

            SystemHeader systemHeader = CreateSystemHeader();

            int size = StructConverter.SizeOf(systemHeader) + day.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(day);
                    writer.Write(new byte[] { 0, 0 });
                    return stream.ToArray();
                }
            }
        }


        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="data"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        private AuthorizationReply? DecodeAuthorizationPacketReply(byte[] data, int startIndex)
        {
            return StructConverter.BytesToStruct(data, startIndex, typeof(AuthorizationReply)) as AuthorizationReply?;
        }

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

            int startIndex = StructConverter.SizeOf(context.SystemHeader);

            AuthorizationReply? reply = DecodeAuthorizationPacketReply(context.Data, startIndex);

            if (reply.HasValue)
            {
                //var authorizationHost = HostRepository.GetByIP(context.RemoteEndPoint.Address.ToString());

                //if (authorizationHost != null)
                //{
                //    Int32 authorizationTime = System.BitConverter.ToInt32(reply.Value.Time, 0);

                //    authorizationHost.AuthorizedHours = authorizationTime;

                //    HostRepository.Update(authorizationHost);
                //}
            }
        }

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