using System;
using Minntech.Comm;
using Minntech.Common;

namespace Minntech.SerialDevices
{

	#region CommPortController interface
	
	public interface ICommPortController
	{
		ICommDevice						Comm	{get; set; }
		Logging.Log						Log		{get; set; }
	}

	#endregion

	#region SerialDevice interface

	public delegate void RecordReceivedEventHandler	(object sender, RecordReceivedEventArgs	e);
	public class RecordReceivedEventArgs : System.EventArgs
	{
		private string _record;
		public RecordReceivedEventArgs (string Record)
		{
			this._record = Record;
		}
		public string Record
		{
			get { return this._record; }
			set { this._record = value;}
		}
	}
	public enum SupportedSerialDevices
	{
		//TODO: update with any newly support comm devices
		DSD201,
		DSD201SoftwareSimulation
	}

	public interface ISerialDevice : ICommPortController, IDisposable
	{
		SupportedSerialDevices				Device	{get; }	
		event RecordReceivedEventHandler	RecordReceived ;
	}

	
	#endregion

	#region specialized exception class

	public class SerialDeviceException : System.Exception
	{
		public CommPortSettings		CurrentSettings;
		public byte[]				CurrentBuffer;
		public CommEvent			EventType;

		#region constructors

		public SerialDeviceException (	
			CommPortSettings Settings, 
			byte[]			 Buffer, 
			CommEvent		 EventType ) : base()
		{
			CurrentSettings		= Settings;
			CurrentBuffer		= Buffer;
			EventType			= EventType;
		}

		public SerialDeviceException (	
			CommPortSettings Settings, 
			byte[]			 Buffer, 
			CommEvent		 EventType, 
			string			 Message ) : base(Message)
		{
			CurrentSettings		= Settings;
			CurrentBuffer		= Buffer;
			EventType			= EventType;
		}
		
		public SerialDeviceException (	
			CommPortSettings Settings, 
			byte[]			 Buffer, 
			CommEvent		 EventType, 
			string			 Message, 
			Exception		 InnerException) : base(Message, InnerException)
		{
			CurrentSettings		= Settings;
			CurrentBuffer		= Buffer;
			EventType			= EventType;
		}
		#endregion
	}

	
	#endregion

	/// <summary>
	/// Summary description for SerialDevices.
	/// </summary>
	public class SerialDevices
	{

		public SerialDevices()
		{
		}
	
		public ISerialDevice SerialDevice( SupportedSerialDevices Device ) 
		{
			ISerialDevice rtnDevice = null;
			try
			{
				//TODO: update with any newly support serial devices
				switch ( Device )
				{
					case SupportedSerialDevices.DSD201:
						rtnDevice = (ISerialDevice)(new DSD201());
						break;
					case SupportedSerialDevices.DSD201SoftwareSimulation:
						rtnDevice = (ISerialDevice)(new DSD201Simulation());
						break;
				}
				return rtnDevice;
			}
			catch ( Exception DeviceErr )
			{
				ErrorHandler.GetInstance().LogException("SerialDevices.SerialDevice", DeviceErr);
				throw DeviceErr;
			}
			finally
			{
				rtnDevice.Dispose();
			}
		}
	}
}

