using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Common;
using Dao;
using Domain;
using RCUHost.Protocols;

namespace RCUHost.Implement
{
    /// <summary>
    /// 专门处理升级完成时更新使用
    /// </summary>
    public class UpdateHostCompletedReceiver : GenericReceiverBase, IUpdateHostReceiver
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(UpdateHostCompletedReceiver));
        public IHostRepository HostRepository { get; set; }
        public IHostUpdateStatusRepository HostUpdateStatusRepository { get; set; }
        private IList<UpdateHostWorker> updateHostList = new List<UpdateHostWorker>();

        public void Update(HostUpdate hostUpdate, FileType fileType, string fileHref, string fileMd5, IList<Host> hosts)
        {
        }

        public override void Process(ReceiverContext context)
        {
            int startIndex = StructConverter.SizeOf(context.SystemHeader);
            UpdateHostPacketReply? reply = DecodeUpdateHostPacketReply(context.Data, startIndex);
            if (reply.HasValue)
            {
                //logger.Error(string.Format("收到tftp升级回复命令（{0}:{1}）：{2}", context.RemoteEndPoint.Address.ToString(), context.RemoteEndPoint.Port, Tools.ByteToString(context.Data)));
                var updateHostWorker = this.updateHostList.FirstOrDefault(r => r.Host.SysHotel.Code == context.SystemHeader.Value.HostNumber.ToHotelCode().ToString() && r.Host.HostNumber == context.SystemHeader.Value.HostNumber.ToString());
                if (updateHostWorker != null)
                {

                    string Upgrade_Status = "";
                    HostUpdateStatus hostUpdateStatus = HostUpdateStatusRepository.Get(updateHostWorker.Host, updateHostWorker.HostUpdate);
                    if (hostUpdateStatus == null)
                    {
                        hostUpdateStatus = new HostUpdateStatus();
                        hostUpdateStatus.Host = updateHostWorker.Host;
                        hostUpdateStatus.HostUpdate = updateHostWorker.HostUpdate;
                        hostUpdateStatus.PublishTime = DateTime.Now;
                        hostUpdateStatus.Status = 0;
                    }
                    switch (reply.Value.Status)
                    {
                        case UpdateHostPacketReply.Ready:
                            hostUpdateStatus.Status = 0;//升级就绪
                            Upgrade_Status = "升级就绪";
                            break;
                        case UpdateHostPacketReply.Completed:
                            Upgrade_Status = "升级完成";
                            Reply(context);//升级完成回复主机
                            hostUpdateStatus.Status = 1;//升级完成
                            updateHostList.Remove(updateHostWorker);
                            break;
                        default:
                            Upgrade_Status = "升级失败";
                            hostUpdateStatus.Status = 2;//升级失败
                            updateHostList.Remove(updateHostWorker);
                            break;
                    }

                    BarData bbb = new BarData();
                    bbb.HostID = updateHostWorker.Host.ID;
                    bbb.Upgrade_status = Upgrade_Status;
                    UploadCurrentVersionReceiver.UP_Grade_Json(updateHostWorker.Host, bbb);

                    hostUpdateStatus.UpdatedTime = DateTime.Now;
                    HostUpdateStatusRepository.SaveOrUpdate(hostUpdateStatus);
                }
                else
                {
                    Host host = HostRepository.GetByHostNumber(context.SystemHeader.Value.HostNumber.ToString());
                    if (host != null)
                    {
                        string Upgrade_Status = "";
                        switch (reply.Value.Status)
                        {
                            case UpdateHostPacketReply.Ready:
                                host.UpgradeStatus = 0;//升级就绪
                                Upgrade_Status = "升级就绪";
                                break;
                            case UpdateHostPacketReply.Completed:
                                Reply(context);//升级完成回复主机
                                host.UpgradeStatus = 1;//升级完成
                                Upgrade_Status = "升级完成";
                                break;
                            default:
                                host.UpgradeStatus = 2;//升级失败
                                Upgrade_Status = "升级失败";
                                break;
                        }
                        BarData bbb = new BarData();
                        bbb.HostID = host.ID;
                        bbb.Upgrade_status = Upgrade_Status;
                        bbb.Upgrade_DateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        UploadCurrentVersionReceiver.UP_Grade_Json(host, bbb);


                        host.UpgradeTime = DateTime.Now;
                        HostRepository.Update(host);
                    }
                }
            }
        }
        public override CommandType CommandType
        {
            get { return CommandType.UpdateHost; }
        }
        #region Private Methods
        /// <summary>
        /// 解码 UpdateHostPacketReply
        /// </summary>
        /// <param name="data"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        private UpdateHostPacketReply? DecodeUpdateHostPacketReply(byte[] data, int startIndex)
        {
            return StructConverter.BytesToStruct(data, startIndex, typeof(UpdateHostPacketReply)) as UpdateHostPacketReply?;
        }

        #endregion
    }
}