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

namespace RCUHost.Implement
{
	public class NetworkSettingReceiver : GenericReceiverBase, INetworkSettingReceiver
	{
		public bool SetNetwork(Domain.Host host, string ip, string subnetmask, string gateway, int port)
		{
			byte[] data = CreateDataPacket(ip, subnetmask, gateway, port);

            SendAndPushCommandQueue(data, host.HostNumber, host.MAC);// host.IP, host.Port);

			return true;
		}

		private byte[] CreateDataPacket(string ip, string subnetmask, string gateway, int port)
		{
			using (MemoryStream stream = new MemoryStream())
			{
				var headerLen = StructConverter.SizeOf(typeof(SystemHeader));

				stream.Seek(headerLen, SeekOrigin.Begin);

				stream.Write(IPAddress.Parse(ip).GetAddressBytes(), 0, 4);
				stream.Write(IPAddress.Parse(subnetmask).GetAddressBytes(), 0, 4);
				stream.Write(IPAddress.Parse(gateway).GetAddressBytes(), 0, 4);
				stream.Write(BitConverter.GetBytes((ushort)port), 0, 2);
				stream.Write(new byte[] { 0, 0 }, 0, 2);

				var header = CreateSystemHeader((int)stream.Length - headerLen);

				byte[] headerData = StructConverter.StructToBytes(header);
				
				stream.Seek(0, SeekOrigin.Begin);
				stream.Write(headerData, 0, headerData.Length);

				return stream.ToArray();
			}
		}

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