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

namespace RCUHost.Implement
{
    /// <summary>
    /// 发送命令给rcu，设置密钥
    /// </summary>
    public class DeviceSecretReceiver : GenericReceiverBase, IDeviceSecretReceiver
	{
        public void Send(Host host)
		{
            var data = CreateDeviceSecretPacket(host);
            SendAndPushCommandQueue(data, host.HostNumber, host.MAC);// host.IP, host.Port);
		}

        private byte[] CreateDeviceSecretPacket(Host host)
		{
			SystemHeader systemHeader = CreateSystemHeader();
            byte[] deviceSecretDataPacket = CreateDeviceSecretDataPacket(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[] CreateDeviceSecretDataPacket(Host host)
        {
            using (MemoryStream buffer = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(buffer))
                {
                    writer.Write(System.Text.Encoding.Default.GetBytes("TSW1"));//小主机TSW1
                    byte[] mac = new byte[host.DeviceName.Length / 2];
                    for (int i = 0; i < mac.Length; i++)
                    {
                        writer.Write(Convert.ToByte(host.DeviceName.Substring(i * 2, 2), 16));//MAC 6字节
                    }
                    writer.Write(System.Text.Encoding.Default.GetBytes(host.DeviceSecret));
                    return buffer.ToArray();
                }
            }
        }

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