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

namespace RCUHost.Implement
{
    /// <summary>
    /// 透传
    /// </summary>
    public class TouChuang : GenericReceiverBase, IHostTouChuan
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(TouChuang));
        public void Send(string HostNumber, string MAC, byte[] sendData, byte SelfCommandType, bool isoriginal = false)
        {
            if (isoriginal)
            {
                Send(sendData, HostNumber, MAC);
            }
            else
            {
                CommandType TTT = (CommandType)SelfCommandType;
                var data = CreateHostSecretPacket(sendData, TTT);
                Send(data, HostNumber, MAC);
            }
        }

        public byte[] CreateHostSecretPacket(byte[] data, CommandType TTT)
        {
            SystemHeader systemHeader = CreateSystemHeaderOverWrite(TTT, 0);
            //加2是 最后是CRC
            int size = StructConverter.SizeOf(systemHeader) + data.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(data);
                    writer.Write(new byte[] { 0, 0 });
                    return stream.ToArray();
                }
            }
        }

        protected SystemHeader CreateSystemHeaderOverWrite(CommandType commandType, int dataLength)
        {
            var systemHeader = new SystemHeader();
            systemHeader.Signature = SystemHeader.SIGNATURE;
            systemHeader.FrameLength = (ushort)(StructConverter.SizeOf(systemHeader) + dataLength);
            systemHeader.SystemID = SystemHeader.SYSTEM_ID.ToCharArray();
            systemHeader.CmdType = (byte)commandType;
            systemHeader.FrameNo = GetNextFrameNo();
            systemHeader.HostNumber = new HostNumber { NBuild = 0xFF, NFloor = 0xFF, NRoom = 0xFF, NUnit = 0xFF };
            return systemHeader;
        }

        public override void Process(ReceiverContext context)
        {

        }

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