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

namespace RCUHost.Implement
{
    /// <summary>
    /// 酒店上下午时间：白天黑夜处理
    /// </summary>
    public class HotelTimeReceiver : GenericReceiverBase, IHotelTimeReceiver
    {
        //private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HotelTimeReceiver));

        /// <summary>
        /// 下发白天黑夜
        /// </summary>
        /// <param name="host"></param>
        public void Send(Host host)
        {
            var data = CreateDevicePacket(host);
            SendAndPushCommandQueue(data, host.HostNumber, host.MAC);
        }

        public override void Process(ReceiverContext context)
        {
            //logger.Error(string.Format("收到白天起始时间命令回复，编码：{0}，IP：{1}", context.SystemHeader.Value.HostNumber.ToString(), context.RemoteEndPoint.Address.ToString() + ":" + context.RemoteEndPoint.Port.ToString()));
        }

        private byte[] CreateDevicePacket(Host host)
        {
            SystemHeader systemHeader = CreateSystemHeader();
            byte[] deviceSecretDataPacket = CreateDeviceDataPacket(host);
            int size = StructConverter.SizeOf(systemHeader) + deviceSecretDataPacket.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(deviceSecretDataPacket);
                    writer.Write(new byte[] { 0, 0 });
                    return stream.ToArray();
                }
            }
        }
        /// <summary>
        /// 下发内容
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        private byte[] CreateDeviceDataPacket(Host host)
        {
            using (MemoryStream buffer = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(buffer))
                {
                    writer.Write(new byte[] { (byte)host.SysHotel.StartDayTime, (byte)host.SysHotel.EndDayTime });
                    return buffer.ToArray();
                }
            }
        }

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