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

namespace RCUHost.Implement
{
	public class EnergySavingModeReceiver : GenericReceiverBase, IEnergySavingModeReceiver
	{
		public void ApplyEnergySavingMode(Model model, Host host)
		{
			byte[] data = CreateEnergySavingModeRequestPacket(model);

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

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

		#region Private Methods

		private byte[] CreateEnergySavingModeRequestPacket(Model model)
		{
			SystemHeader systemHeader = CreateSystemHeader();

			EnergySavingModePacket energySavingModePacket = CreateEnergySavingModePacket(model);

			int size = StructConverter.SizeOf(systemHeader) + StructConverter.SizeOf(energySavingModePacket);

			systemHeader.FrameLength = (ushort)size;

			byte[] buffer = new byte[size];

			byte[] src1 = StructConverter.StructToBytes(systemHeader);
			Array.Copy(src1, 0, buffer, 0, src1.Length);

			byte[] src3 = StructConverter.StructToBytes(energySavingModePacket);
			Array.Copy(src3, 0, buffer, src1.Length, src3.Length);

			return buffer;
		}

		private EnergySavingModePacket CreateEnergySavingModePacket(Model model)
		{
			EnergySavingModePacket packet = new EnergySavingModePacket();

			packet.CorrectedTemp = Convert.ToByte(model.CorrectedTemp);
			packet.FanRunStatus = Convert.ToByte(model.FanRunStatus ? 1 : 0);
			packet.ExhaustFanStatus = Convert.ToByte(model.ExhaustFanStatus);
			packet.ExhaustFanTime = Convert.ToByte(model.ExhausFanTime);

			packet.InfraredDelayPO = Convert.ToByte(model.InfraredDelayPO);
			packet.DoorDelayPO = Convert.ToByte(model.DoorDelayPO);
			packet.PullCardDelayPO = Convert.ToByte(model.PullCardDelayPO);

			ModelDetail detail1 = model.Details.FirstOrDefault(r => r.ModelStatus == "插卡时");
			ModelDetail detail2 = model.Details.FirstOrDefault(r => r.ModelStatus == "拔卡时");
			ModelDetail detail3 = model.Details.FirstOrDefault(r => r.ModelStatus == "待租时");
			ModelDetail detail4 = model.Details.FirstOrDefault(r => r.ModelStatus == "停租时");

			packet.FengJiStatus = new FengJiStatus[4]
			{
				CreateFengJiStatus(detail1),
				CreateFengJiStatus(detail2),
				CreateFengJiStatus(detail3),
				CreateFengJiStatus(detail4)
			};

			return packet;
		}

		private FengJiStatus CreateFengJiStatus(ModelDetail detail)
		{
			return new FengJiStatus
			{
				OnOff = detail.OnOff,
				Type = Convert.ToByte(detail.ModelType),
				Speed = Convert.ToByte(detail.Speed),
				SummerTemp = Convert.ToByte(detail.SummerTemp),
				WinterTemp = Convert.ToByte(detail.WinterTemp),
				TimingControl = Convert.ToByte(detail.TimingControl ? 1 : 0),
				Timer = Convert.ToByte(detail.Timer),
				AllowElectric = Convert.ToByte(detail.AllowElectric ? 1 : 0),
			};
		}

		#endregion
	}
}

