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

namespace RCUHost.Implement
{
    public class UpdateRCUFileReceiver : GenericReceiverBase, IUpdateRCUFileReceiver
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(UpdateRCUFileReceiver));

        public IHostRepository HostRepository { get; set; }

        public void Update(HostUpdate hostUpdate, IList<Host> hosts)
        {
            if (hosts == null || hosts.Count == 0)
            {
                throw new ApplicationException("更新失败，没有找到需要更新有效期的主机。");
            }

            if (String.IsNullOrEmpty(hostUpdate.Href))
            {
                throw new ApplicationException("更新失败，无效的RCU有效期文件。");
            }

            string updateFile = Tools.GetApplicationPath() + hostUpdate.Href;
            if (!File.Exists(updateFile))
            {
                throw new ApplicationException("更新失败，【" + updateFile + "】不是有效的RCU有效期文件。");
            }

            string strLicense = "";
            if (!Common.MyDes.DecodeFromFile(updateFile, ref strLicense))
            {
                throw new ApplicationException("更新失败，【" + updateFile + "】无效的RCU有效期文件。");
            }
            License license = Common.MyDes.ReadLicense(strLicense);
            if (license.SystemTypeID != 3)
            {
                throw new ApplicationException("更新失败，【" + updateFile + "】RCU有效期文件系统类型有误。");
            }

            ushort days = Convert.ToUInt16((DateTime.Parse(license.EndDate.ToString("yyyy-MM-dd " + DateTime.Now.ToLongTimeString())) - DateTime.Now).TotalDays);

            foreach (var host in hosts)
            {
                try
                {
                    //先去掉加密
                    //Send(CreateDataPacket(days), host.HostNumber, host.MAC);//host.IP, host.Port);
                    host.AuthorizedHours = days;
                    HostRepository.Update(host);
                    //this.updateHostList.Add(new UpdateHostWorker(host, hostUpdate));
                }
                catch (Exception) { }
            }

            //FileInfo fileInfo = new FileInfo(updateFile);
            //ushort blockNum = (ushort)Math.Ceiling((double)fileInfo.Length / BLOCK_SIZE);
            //this.updateHostList.Clear();

            //foreach (var host in hosts)
            //{
            //    SendUpdateRequest(host, hostUpdate.Md5, blockNum);
            //    this.updateHostList.Add(new UpdateHostWorker(host, hostUpdate));
            //}
        }

        private byte[] CreateDataPacket(ushort days)
        {
            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();
                }
            }
        }

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

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

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

            //if (reply.HasValue)
            //{
            //    try
            //    {
            //        var authorizationHost = HostRepository.GetByHostNumber(context.SystemHeader.Value.HostNumber.ToString());

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

            //            authorizationHost.AuthorizedHours = authorizationTime;

            //            HostRepository.Update(authorizationHost);
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        if (logger.IsErrorEnabled)
            //        {
            //            string msg = context.RemoteEndPoint.Address.ToString() + ":" + context.RemoteEndPoint.Port.ToString() + ":" + Tools.ByteToString(context.Data);
            //            logger.Error("解析升级主机有效期数据出错【" + msg + "】", ex);
            //        }
            //    }
            //}
        }

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

        /// <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?;
        }
    }
}
