//                           UNCLASSIFIED
/*-------------------------------------------------------------------------
RAYTHEON PROPRIETARY: THIS DOCUMENT CONTAINS DATA OR INFORMATION
PROPRIETARY TO RAYTHEON COMPANY AND IS RESTRICTED TO USE ONLY BY PERSONS
AUTHORIZED BY RAYTHEON COMPANY IN WRITING TO USE IT. DISCLOSURE TO
UNAUTHORIZED PERSONS WOULD LIKELY CAUSE SUBSTANTIAL COMPETITIVE HARM TO
RAYTHEON COMPANY'S BUSINESS POSITION. NEITHER SAID DOCUMENT NOR ITS
CONTENTS SHALL BE FURNISHED OR DISCLOSED TO OR COPIED OR USED BY PERSONS
OUTSIDE RAYTHEON COMPANY WITHOUT THE EXPRESS WRITTEN APPROVAL OF RAYTHEON
COMPANY.

THIS PROPRIETARY NOTICE IS NOT APPLICABLE IF DELIVERED TO THE U.S.
GOVERNMENT.

UNPUBLISHED WORK - COPYRIGHT RAYTHEON COMPANY.
-------------------------------------------------------------------------*/

using NLog;
using Raytheon.Common;
using System;
using System.Collections.Generic;
using System.Threading;

namespace Raytheon.Instruments
{
	/// <summary>
	/// A simulated fpga
	/// </summary>
	public class CommFpgaSim : IFpgaComm
	{
		#region PrivateClassMembers
		private Dictionary<uint, uint> _registers;
		private static object _syncObj = new Object();
		private SelfTestResult _selfTestResult;
		private State _state;
		private string _name;

		/// <summary>
		/// NLog logger
		/// </summary>
		private readonly ILogger _logger;
		/// <summary>
		/// Raytheon configuration
		/// </summary>
		private readonly IConfigurationManager _configurationManager;
		private readonly IConfiguration _configuration;

		#endregion

		#region PrivateFunctions
		/// <summary>
		/// The finalizer.
		/// </summary>
		~CommFpgaSim()
		{
			Dispose(false);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="disposing"></param>
		protected virtual void Dispose(bool disposing)
		{
			try
			{
				if (disposing)
				{
				}
			}
			catch (Exception)
			{
				try
				{
					//ErrorLogger.Instance().Write(err.Message + "\r\n" + err.StackTrace);
				}
				catch (Exception)
				{
					//Do not rethrow. Exception from error logger that has already been garbage collected
				}
			}
		}
		#endregion

		#region PublicFuctions

		/// <summary>
		/// CommFpgaSim factory constructor
		/// </summary>
		/// <param name="deviceName"></param>
		/// <param name="configurationManager"></param>
		public CommFpgaSim(string deviceName, IConfigurationManager configurationManager, ILogger logger)
		{
			Name = deviceName;

			_logger = logger;

			_configurationManager = configurationManager;
			_configuration = _configurationManager.GetConfiguration(Name);

			_selfTestResult = SelfTestResult.Unknown;
			_state = State.Uninitialized;
			_registers = null;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="name"></param>
		public CommFpgaSim(string name)
		{
			_name = name;
			_logger = LogManager.GetCurrentClassLogger();
			_selfTestResult = SelfTestResult.Unknown;
			_state = State.Uninitialized;
			_registers = null;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public bool ClearErrors()
		{
			return false;
		}

		/// <summary>
		/// 
		/// </summary>
		public string DetailedStatus
		{
			get
			{
				return "This is a FPGA Sim called " + _name;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public bool DisplayEnabled
		{
			get
			{
				return false;
			}

			set
			{
				throw new NotImplementedException();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public void Dispose()
		{
			lock (_syncObj)
			{
				try
				{
					Dispose(true);

					GC.SuppressFinalize(this);
				}
				catch (Exception)
				{
					try
					{
						//ErrorLogger.Instance().Write(err.Message + "\r\n" + err.StackTrace);
					}
					catch (Exception)
					{
						//Do not rethrow. Exception from error logger that has already been garbage collected
					}
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public bool FrontPanelEnabled
		{
			get
			{
				return false;
			}

			set
			{
				throw new NotImplementedException();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public InstrumentMetadata Info
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public void Initialize()
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="fpga"></param>
		public void Initialize(string fpga)
		{
			lock (_syncObj)
			{
				if (_state == State.Uninitialized)
				{
					_state = State.Ready;
					_registers = new Dictionary<uint, uint>();
				}
				else
				{
					throw new Exception("expected the state to be Uninitialized, state was: " + _state.ToString() + " on card " + _name);
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public string Name
		{
			get
			{
				return _name;
			}
			set { _name = value; }
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public SelfTestResult PerformSelfTest()
		{
			_selfTestResult = SelfTestResult.Unknown;
			return _selfTestResult;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="fpgaName"></param>
		/// <param name="address"></param>
		/// <returns></returns>
		public uint Read(string fpgaName, uint address)
		{
			lock (_syncObj)
			{
				Thread.Sleep(50);

				if (_registers.ContainsKey(address) == true)
				{
					return _registers[address];
				}
				else
				{
					return 0xffffffff;
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="fpgaName"></param>
		/// <param name="address"></param>
		/// <param name="numberOfWordsToRead"></param>
		/// <param name="shallWeIncrementAddress"></param>
		/// <param name="dataRead"></param>
		public void ReadBlock(string fpgaName, uint address, uint numberOfWordsToRead, bool shallWeIncrementAddress, ref uint[] dataRead)
		{
			lock (_syncObj)
			{
				Thread.Sleep(50);

				for (int i = 0; i < numberOfWordsToRead; i++)
				{
					dataRead[i] = Read(fpgaName, address);

					if (shallWeIncrementAddress == true)
					{
						address += 4;
					}
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public void Reset()
		{
			Shutdown();

			Initialize();
		}

		/// <summary>
		/// 
		/// </summary>
		public SelfTestResult SelfTestResult
		{
			get
			{
				return _selfTestResult;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public State Status
		{
			get
			{
				return _state;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public void Shutdown()
		{
			_state = State.Uninitialized;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="fpgaName"></param>
		/// <param name="address"></param>
		/// <param name="value"></param>
		public void Write(string fpgaName, uint address, uint value)
		{
			lock (_syncObj)
			{
				Thread.Sleep(50);

				_registers[address] = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="fpgaName"></param>
		/// <param name="address"></param>
		/// <param name="numberOfWordsToWrite"></param>
		/// <param name="data"></param>
		/// <param name="shallWeIncrementAddress"></param>
		public void WriteBlock(string fpgaName, uint address, uint numberOfWordsToWrite, uint[] data, bool shallWeIncrementAddress)
		{
			lock (_syncObj)
			{
				Thread.Sleep(50);

				for (int i = 0; i < numberOfWordsToWrite; i++)
				{
					uint dataItem = data[i];

					Write(fpgaName, address, dataItem);

					if (shallWeIncrementAddress == true)
					{
						address += 4;
					}
				}
			}
		}

		/// <summary>
		/// Loads firmware
		/// </summary>
		/// <param name="fpgaName"></param>
		public void LoadFirmware(string fpgaName)
		{
			Initialize(fpgaName);
		}

		#endregion
	}
}
