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

namespace RCUHost.Implement
{
	public class ConnectingRoomReceiver : GenericReceiverBase, IConnectingRoomReceiver
	{
		/// <summary>
		/// 设置/取消连通房
		/// </summary>
		/// <param name="hostList"></param>
		/// <param name="cancel">false/设置连通房，true/取消连通房，默认false</param>
		public void ConnectRoom(IList<Host> hostList, bool cancel = false)
		{
			byte[] data = CreateDataPacket(hostList, cancel);

			foreach (var host in hostList)
			{
                Send(data, host.HostNumber, host.MAC);// host.IP, host.Port);
			}
		}

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

		public byte[] CreateDataPacket(IList<Host> hostList, bool cancel)
		{
			int headerSize = StructConverter.SizeOf(typeof(SystemHeader));

			using (MemoryStream stream = new MemoryStream())
			{
				stream.Seek(headerSize, SeekOrigin.Begin);

				stream.WriteByte((byte)(cancel ? 0 : 1));
				stream.WriteByte((byte)hostList.Count);
				foreach (var host in hostList)
				{
					stream.Write(IPAddress.Parse(host.IP).GetAddressBytes(), 0, 4);
				}

				stream.Write(new byte[] { 0, 0 }, 0, 2);

				var header = CreateSystemHeader((int)stream.Length - headerSize);
				var headerData = StructConverter.StructToBytes(header);

				stream.Seek(0, SeekOrigin.Begin);
				stream.Write(headerData, 0, headerData.Length);

				return stream.ToArray();
			}
		}
	}
}
