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

namespace RCUHost.Implement
{
    /// <summary>
    /// 上传RCU软件当前版本号 RCU -> 服务器
    /// </summary>
    public class UploadCurrentVersionReceiver : GenericReceiverBase
    {
        public IHostRepository HostRepository { get; set; }

        public IHostUpdateStatusRepository HostUpdateStatusRepository { get; set; }

        public override void Process(ReceiverContext context)
        {
            //base.Process(context);
            int startIndex = StructConverter.SizeOf(context.SystemHeader);
            UploadCurrentVersionPacketReply? packet = DecodeUploadCurrentVersionPacketReply(context.Data, startIndex);
            if (packet.HasValue)
            {
                Host host = HostRepository.GetByHostNumber(context.SystemHeader.Value.HostNumber.ToString());//(context.RemoteEndPoint.Address.ToString());
                if (host != null)
                {
                    HostUpdateStatus hostUpdateStatus = HostUpdateStatusRepository.Get(host, 0);
                    if (hostUpdateStatus != null)
                    {
                        //更新 HostUpdateStatus
                        if (host.Version != packet.Value.Version)
                        {
                            hostUpdateStatus.Status = 1;
                            hostUpdateStatus.UpdatedTime = DateTime.Now;
                            HostUpdateStatusRepository.Update(hostUpdateStatus);
                        }
                    }
                    //更新版本号
                    if (host.Version != packet.Value.Version)
                    {
                        host.Version = packet.Value.Version;
                        HostRepository.Update(host);

                        BarData bbb = new BarData();
                        bbb.HostID = host.ID;
                        bbb.Version = host.Version;
                        UP_Grade_Json(host, bbb);
                    }
                }
            }
        }

        public static void UP_Grade_Json(Host host, BarData bbb)
        {
            try
            {
                if (string.IsNullOrEmpty(bbb.Upgrade_status))
                {
                    return; 
                }
                string id = host.ID.ToString();
                string Key = CacheKey.UPGradeProgressBar + "_" + id;
                var DDD = CSRedisCacheHelper.Get<BarData>(Key);
                if (DDD != null)
                {
                    DDD.BaiFenBi = bbb.BaiFenBi;
                    DDD.Upgrade_status = bbb.Upgrade_status;
                    DDD.Upgrade_DateTime = bbb.Upgrade_DateTime;
                    DDD.Version = bbb.Version;
                    DDD.ConfiguraVersion = bbb.ConfiguraVersion;
                    DDD.FileBlockTotalCount = bbb.FileBlockTotalCount;
                    DDD.FileCurrentNumber = bbb.FileCurrentNumber;
                    CSRedisCacheHelper.Set(Key, DDD);
                }
                else
                {
                    CSRedisCacheHelper.Set(Key, bbb);
                }
                string str = Newtonsoft.Json.JsonConvert.SerializeObject(bbb);
                int hotelid = host.SysHotel.ID;
                string debug_log_report_url = RCUHost.TimingHelper.Common.debug_log_report_url;
                string debug_log_report_mqtt_topic = "blw/upgrade_progress/report/" + hotelid;

                var client1 = new RestClient(debug_log_report_url);
                var request1 = new RestRequest("/", Method.POST);

                //注意方法是POST
                //两个参数名字必须是 topic 和payload ，区分大小写的
                request1.AddParameter("topic", debug_log_report_mqtt_topic);
                request1.AddParameter("payload", str);
                client1.ExecuteAsync(request1, (response) => { });
            }
            catch (Exception)
            {

            }
        }

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

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