//                           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 FpgaMeasurementInstrumentsLib;
using NLog;
using Raytheon.Common;
using System;

namespace Raytheon.Instruments
{
	/// <summary>
	/// A class that implements the Teradyne HSS Sub System Card
	/// </summary>
	public class CommFpgaHssubCardSs : IFpgaComm
	{
		#region PrivateClassMembers
		private readonly string _name;
		private readonly string _cardAddress;
		private readonly uint _startingOffset;
		private readonly string _firmware;
		private readonly string _memMap;
		private uint _cardHandle;
		private SelfTestResult _selfTestResult;

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

		public string DetailedStatus => throw new NotImplementedException();

		public bool DisplayEnabled { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
		public bool FrontPanelEnabled { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

		public InstrumentMetadata Info => throw new NotImplementedException();

		public string Name { get; set; }

		public SelfTestResult SelfTestResult => throw new NotImplementedException();

		public State Status => throw new NotImplementedException();

		#endregion

		#region PrivateFunctions

		/// <summary>
		/// 
		/// </summary>
		/// <param name="disposing"></param>
		protected virtual void Dispose(bool disposing)
		{
			try
			{
				if (disposing)
				{
					int ret = HssubNativeMethods.terHsi_close(_cardHandle);
				}
			}
			catch (Exception err)
			{
				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 void LoadFirmware()
		{
			ushort customerId = 0;
			ushort appId = 0;
			uint revId = 0;

			int ret = HssubNativeMethods.terHsi_Firmware_Load(_cardHandle, HssubNativeMethods.TERHSI_FPGA_TEST_DEFINED, _firmware, ref customerId, ref appId, ref revId);
			if (ret != 0)
			{
				string errorStr = HssUtilSs.BuildErrorString(_cardHandle, ret, _name);

				throw new Exception("terHsi_Firmware_Load() returned an error(" + ret + ")" + ": " + errorStr);
			}
		}

		#endregion

		#region PublicFuctions

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

			_logger = logger;

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

			_cardAddress = _configuration.GetConfigurationValue("CommFpgaHssubCardSs", "CardAddress", "127.0.0.1");
			_startingOffset = _configuration.GetConfigurationValue<uint>("CommFpgaHssubCardSs", "StartingOffset", 0);
			_firmware = _configuration.GetConfigurationValue("CommFpgaHssubCardSs", "Firmware", "");
			_memMap = _configuration.GetConfigurationValue("CommFpgaHssubCardSs", "MemMap", "");
			_cardHandle = 0;

			LoadFirmware();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="name"></param>
		/// <param name="cardAddress"></param>
		/// <param name="startingOffset"></param>
		/// <param name="firmware"></param>
		/// <param name="memMap"></param>
		public CommFpgaHssubCardSs(string name, string cardAddress, int startingOffset, string firmware, string memMap)
		{
			// hold onto args
			_name = name;
			_logger = LogManager.GetCurrentClassLogger();
			_cardAddress = cardAddress;
			_startingOffset = (uint)startingOffset;
			_firmware = firmware;
			_memMap = memMap;
			_cardHandle = 0;

			LoadFirmware();
		}

		/// <summary>
		/// The finalizer.
		/// </summary>
		~CommFpgaHssubCardSs()
		{
			Dispose(false);
		}

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

				GC.SuppressFinalize(this);
			}
			catch (Exception err)
			{
				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>
		/// <returns></returns>
		public string GetMemMap()
		{
			return _memMap;
		}

		/// <summary>
		/// reads FPGA value from address
		/// </summary>
		/// <param name="fpgaName"></param>
		/// <param name="address"></param>
		/// <returns></returns>
		/// <exception cref="Exception"></exception>
		public uint Read(string fpgaName, uint address)
		{
			uint dataRead = 0;
			int ret = HssubNativeMethods.terHsi_LB_Read32(_cardHandle, _startingOffset + address, ref dataRead);
			if (ret != 0)
			{
				string errorStr = HssUtilSs.BuildErrorString(_cardHandle, ret, _name);

				throw new Exception("terHsi_LB_Read32() returned an error(" + ret + ")" + ": " + errorStr);
			}

			return dataRead;
		}

		/// <summary>
		/// reads block
		/// </summary>
		/// <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)
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// writes value to fpga address
		/// </summary>
		/// <param name="address"></param>
		/// <param name="value"></param>
		public void Write(string fpgaName, uint address, uint value)
		{
			int ret = HssubNativeMethods.terHsi_LB_Write32(_cardHandle, _startingOffset + address, value);
			if (ret != 0)
			{
				string errorStr = HssUtilSs.BuildErrorString(_cardHandle, ret, _name);

				throw new Exception("terHsi_LB_Write32() returned an error(" + ret + ")" + ": " + errorStr);
			}
		}

		/// <summary>
		/// writes block
		/// </summary>
		/// <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)
		{
			throw new Exception("Not Implemented");
		}

		/// <summary>
		/// initialize fpga
		/// </summary>
		/// <param name="fpgaName"></param>
		public void Initialize(string fpgaName)
		{
			Initialize();
		}

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

		public bool ClearErrors()
		{
			return false;
		}

		public void Initialize()
		{
			LoadFirmware();
		}

		public SelfTestResult PerformSelfTest()
		{
			_selfTestResult = SelfTestResult.Unknown;
			return _selfTestResult;
		}

		public void Reset()
		{
			Shutdown();

			Initialize();
		}

		public void Shutdown()
		{
			Dispose();
		}
		#endregion
	}
}
