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

namespace RCUHost.Implement
{
    public class SyncTimeReceiver : GenericReceiverBase, ISyncTimeReceiver
    {
        public ISysHotelRepository SysHotelRepository { get; set; }

        private System.Timers.Timer timer;

        //protected override void HostServer_AfterStart(HostServer hostServer)
        //{
        //    Start();
        //}

        public override void Process(ReceiverContext context)
        {
            bool bkb = GenericReceiverBase.DealWwith(context);
            if (bkb == false)
            {
                return;
            }
            int startDayTime = 6;//白天开始时间
            int endDayTime = 18;//白天截止时间

            string hotelCode = context.SystemHeader.Value.HostNumber.ToHotelCode().ToString();

            string HostNumberOnly = context.SystemHeader.Value.HostNumber.ToString();
            //如果超过2秒就不再处理了
            string ShiJianLanJie = CacheKey.SyncTimeIntercept + "_" + HostNumberOnly;
            object VVV = MemoryCacheHelper.Get(ShiJianLanJie);
            if (VVV == null)
            {
                string RegisterKey1 = "SyncTimeTimeOutDrop";
                RCUHost.RCUHostCommon.tools.LanJieData(RegisterKey1, hotelCode);
                return;
            }


            string Key = CacheKey.HotelInfo_Key_Code + "_" + hotelCode; ;
            object ooo = MemoryCacheHelper.Get(Key);
            SysHotel sysHotel = null;
            if (ooo != null)
            {
                sysHotel = (SysHotel)ooo;
            }
            else
            {
                sysHotel = SysHotelRepository.GetByCode(hotelCode);//获取酒店记录
                MemoryCacheHelper.SlideSet(hotelCode, sysHotel);
            }

            //SysHotel sysHotel = SysHotelRepository.GetByCode(context.SystemHeader.Value.HostNumber.ToHotelCode().ToString());
            if (sysHotel != null)
            {
                startDayTime = sysHotel.StartDayTime;
                endDayTime = sysHotel.EndDayTime;
            }
            byte[] data = CreateSysTimePacket(DateTime.Now, startDayTime, endDayTime);

            ushort frame_no = context.SystemHeader.Value.FrameNo;
            byte[] framenolist = BitConverter.GetBytes(frame_no);
            if (framenolist[0] == 0xFF && framenolist[1] == 0xFF)
            {
                Send(data, context.RemoteEndPoint);
            }
            else
            {
                data[9] = framenolist[0];
                data[10] = framenolist[1];
                Send(data, context.RemoteEndPoint);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="now">当前时间</param>
        /// <param name="startDayTime">白天开始时间</param>
        /// <param name="endDayTime">白天截止时间</param>
        /// <returns></returns>
        private byte[] CreateSysTimePacket(DateTime now, int startDayTime, int endDayTime)
        {
            SystemHeader systemHeader = CreateSystemHeader();

            SyncTimePacket syncTimePacket = new SyncTimePacket
            {
                Year = (ushort)now.Year,
                Month = (byte)now.Month,
                Day = (byte)now.Day,
                Week = (byte)(now.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)now.DayOfWeek),
                Hour = (byte)now.Hour,
                Minute = (byte)now.Minute,
                Second = (byte)now.Second,
                StartDayTime = (byte)startDayTime,
                EndDayTime = (byte)endDayTime
            };

            int size = StructConverter.SizeOf(systemHeader) + StructConverter.SizeOf(syncTimePacket);

            systemHeader.FrameLength = (ushort)size;

            byte[] buffer = new byte[size];

            byte[] data1 = StructConverter.StructToBytes(systemHeader);
            Array.Copy(data1, buffer, data1.Length);

            byte[] data2 = StructConverter.StructToBytes(syncTimePacket);
            Array.Copy(data2, 0, buffer, data1.Length, data2.Length);

            return buffer;
        }

        public void Start()
        {
            if (timer == null)
            {
                timer = new System.Timers.Timer();
                timer.AutoReset = true;
                timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            }

            timer.Interval = 60000;		//每隔60s

            if (!timer.Enabled)
            {
                timer.Start();
            }
        }

        public void Stop()
        {
            if (timer != null)
            {
                timer.Stop();
                timer = null;
            }
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime now = DateTime.Now;
            //整点同步时间
            if (now.Minute == 0)
            {
                //Sync(now, MulticastIP, MulticastPort);
            }
        }

        //private void Sync(DateTime now, string host, int port)
        //{
        //    Sync(now, new IPEndPoint(IPAddress.Parse(host), port));
        //}

        //private void Sync(DateTime now, string hostNumber, string mac)
        //{
        //    byte[] data = CreateSysTimePacket(now);
        //    SendAndPushCommandQueue(data, hostNumber, mac);
        //}

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

    }
}
