using System;
using System.Collections.Generic;
using Medivators.Common;
using Medivators.Common.Enums;
using Medivators.Common.Logging;

namespace Medivators.SerialDevices
{
	/// <summary>
	/// Singleton, typed Queue class to contain raw transmission strings
	/// </summary>
	public class TxQueue : Queue<SerialDeviceTransmission>, IDisposable
	{
		private static TxQueue _instance = null;
		private object _lock = new object();
		private bool _captureInit = false;
		private SerialDeviceCaptureFile _captureFile = null;

		#region singleton construct/init/dispose

		private TxQueue()
		{
		}

		public static TxQueue GetInstance()
		{
			if ( _instance == null )
				_instance = new TxQueue();
			return _instance;
		}
		public void Dispose()
		{
			//flush pending entries to database?
		}

		#endregion 

		public new void Enqueue(SerialDeviceTransmission Tx)
		{
			lock (_lock)
			{
				base.Enqueue(Tx);
				CommCapture(Tx);
			}
			Log.GetInstance().WriteLog(LogEntryType.DebugTrace,
					"TxQueue reports receipt of record [" +
					Tx.ToString(true) +
					"]");
		}
		public new SerialDeviceTransmission Dequeue()
		{
			SerialDeviceTransmission Tx = null;
			lock (_lock)
			{
				Tx = (SerialDeviceTransmission)base.Dequeue();
			}
			Log.GetInstance().WriteLog(LogEntryType.DebugTrace,
				"TxQueue releasing record [" +
				Tx.ToString() +
				"]");
			return Tx;
		}

		#region managing comm capture file

		private void CommCapture(SerialDeviceTransmission Tx)
		{
			//	first-time through code
			if (!_captureInit)
			{
				string setting = TextSettings.GetInstance()[SettingTypes.Application, "CommCaptureFile"];
				if (setting != null && setting.Length > 0)
					if ( !setting.Equals("0") )
					_captureFile = new SerialDeviceCaptureFile(Constants.MedivatorsProgramFiles, "Capture.txt");
				_captureInit = true;
			}
			if (_captureFile != null)
				_captureFile.Capture(Tx);
		}

		#endregion
	}
}
