using System;
using System.IO;
using System.Timers;
using Medivators.Comm;
using Medivators.Common;
using Medivators.Common.Enums;
using Medivators.Common.Logging;

namespace Medivators.SerialDevices
{
	/// <summary>
	/// Summary description for DSD201Simulation
	/// </summary>
	public class DSD201Simulation : DSD201, ISerialDevice, IDisposable
	{
		private Timer			_timer		= null;
		private string			_path		= string.Empty;
		private BinaryReader	_file		= null;
		private int				_interval	= 5000;
		private dlgDSD_201Simulation _dlg	= null;
		private bool			_rollFile	= false;

		public new event RecordReceivedEventHandler	RecordReceived;

		public const int DSD201RecordLength = 35;

		public DSD201Simulation()
		{
			base.RecordReceived += new RecordReceivedEventHandler(DSD201Simulation_RecordReceived);
			_dlg = new dlgDSD_201Simulation(this);
			_dlg.Show();
		}
		public new void Dispose()
		{
			if (_timer != null)
			{
				_timer.Enabled = false;
				_timer.Dispose();
			}
			if ( _dlg != null )
				_dlg.Dispose();
			base.Dispose();
		}

		#region events

		private void OnDataReceived(byte[] Data) 
		{
			base.Log.WriteLog(LogEntryType.DebugTrace, "Simulated DSD201 data received [" +
				Utilities.ByteArrayToString(Data, true) +
				"]");
			base.CommDataArrived(this, new DataArrivedEventArgs(Data));
		}
		private void DSD201Simulation_RecordReceived(object sender, RecordReceivedEventArgs e)
		{
			this.RecordReceived(this, e);
		}

		#endregion

		public string SimulationFilePath
		{
			get { return _path; }
			set 
			{
				if (! _path.Equals(value))
				{
					_path = value;
					if (File.Exists(_path))
					{
						if (_file != null)
						{
							_file.Close();
							_file.BaseStream.Dispose();
						}
						_file = new BinaryReader(File.Open(_path, FileMode.Open, FileAccess.Read));
					}
					else
						throw new ArgumentException("Simulation File " +
							_path +
							" not found!");
				}
			}
		}
		public int RecordReadInterval
		{
			get 
			{
				if (_timer == null)
					return _interval;
				else
					return (int)_timer.Interval;
			}
			set
			{
				_interval = value;
				if (_timer != null)
					_timer.Interval = value;
			}
		}

		public void StartTimer(bool RollFile)
		{
			if (_timer == null)
			{
				_timer = new Timer(_interval);
				_timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
			}
			_timer.Enabled = true;
			_rollFile = RollFile;
		}
		public void StopTimer()
		{
			_timer.Enabled = false;
		}

		internal void Timer_Elapsed ( object sender, ElapsedEventArgs e )
		{
			if (_file != null) 
			{
				int fileLen = (int)_file.BaseStream.Length;
				if ( _file.BaseStream.Position < fileLen )
					OnDataReceived(_file.ReadBytes(DSD201RecordLength));
				else
					if (_rollFile) //	restart at beginning of file
						_file.BaseStream.Position = 0;
			}
		}
	}
}
