//                           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 Raytheon.Instruments;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MeasurementManagerLib
{
	/// <summary>
	/// This class provides an abstraction for running jtag jobs via the command line
	/// </summary>
	public class JtagMeasurementManager : IDisposable
	{
		#region PrivateMembers
		private readonly IJtag _jtag;
		private Dictionary<string, JtagJobInfo> _jtagMeasurements;
      private static NLog.ILogger _logger;
      #endregion

      #region PrivateFunctions

      /// <summary>
      /// Finalizer.
      /// </summary>
      ~JtagMeasurementManager()
		{
			Dispose(false);
		}

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

		/// <summary>
		/// Parses Measurement Definition File
		/// </summary>
		/// <param name="configurationFile"></param>
		private void ParseMeasurementDef(ConfigurationFile configurationFile)
		{
			const string BSX_FILE_PATH_KEY = "BSX_FILE_PATH";
			const string BSX_FILE_KEY = "BSX_FILE";
			const string BSX_COMMAND_LINE_KEY = "BSX_FILE_COMMAND_LINE";

			const string USE_DIAG_CMD_LINE1_KEY = "USE_DIAG_CMD_LINE_1";
			const string DIAG_FILE1_KEY = "DIAG_FILE_1";
			const string DIAG_CMD_LINE1_KEY = "DIAG_CMD_LINE_1";

			const string USE_DIAG_CMD_LINE2_KEY = "USE_DIAG_CMD_LINE_2";
			const string DIAG_FILE2_KEY = "DIAG_FILE_2";
			const string DIAG_CMD_LINE2_KEY = "DIAG_CMD_LINE_2";

			// read in all of the sections
			List<string> sections = configurationFile.ReadAllSections();

			foreach (string section in sections)
			{
				string bsxFilePath = configurationFile.ReadValue<string>(section, BSX_FILE_PATH_KEY);
				string bsxFile = configurationFile.ReadValue<string>(section, BSX_FILE_KEY);
				string bsxCmdLine = configurationFile.ReadValue<string>(section, BSX_COMMAND_LINE_KEY);

				bool useDiag1 = configurationFile.ReadValue<bool>(section, USE_DIAG_CMD_LINE1_KEY);
				string diag1File = "Not Set";
				string diag1CmdLine = "Not Set";
				if (useDiag1 == true)
				{
					diag1File = configurationFile.ReadValue<string>(section, DIAG_FILE1_KEY);
					diag1CmdLine = configurationFile.ReadValue<string>(section, DIAG_CMD_LINE1_KEY);
				}

				bool useDiag2 = configurationFile.ReadValue<bool>(section, USE_DIAG_CMD_LINE2_KEY);
				string diag2File = "Not Set";
				string diag2CmdLine = "Not Set";
				if (useDiag2 == true)
				{
					diag2File = configurationFile.ReadValue<string>(section, DIAG_FILE2_KEY);
					diag2CmdLine = configurationFile.ReadValue<string>(section, DIAG_CMD_LINE2_KEY);
				}

				JtagJobInfo info = new JtagJobInfo
				{
					bsxFilePath = bsxFilePath,
					bsxFile = bsxFile,
					bsxFileCommandline = bsxCmdLine,

					shallWeUseDiag1 = useDiag1,
					diag1File = diag1File,
					diag1CmdLine = diag1CmdLine,

					shallWeUseDiag2 = useDiag2,
					diag2File = diag2File,
					diag2CmdLine = diag2CmdLine
				};

				_jtagMeasurements.Add(section.ToUpper(), info);
			}
		}


		/// <summary>
		/// Parses Measurement Definition File
		/// </summary>
		/// <param name="measurementDefFile"></param>
		private void ParseMeasurementDef(string measurementDefFile)
		{
			const string BSX_FILE_PATH_KEY = "BSX_FILE_PATH";
			const string BSX_FILE_KEY = "BSX_FILE";
			const string BSX_COMMAND_LINE_KEY = "BSX_FILE_COMMAND_LINE";

			const string USE_DIAG_CMD_LINE1_KEY = "USE_DIAG_CMD_LINE_1";
			const string DIAG_FILE1_KEY = "DIAG_FILE_1";
			const string DIAG_CMD_LINE1_KEY = "DIAG_CMD_LINE_1";

			const string USE_DIAG_CMD_LINE2_KEY = "USE_DIAG_CMD_LINE_2";
			const string DIAG_FILE2_KEY = "DIAG_FILE_2";
			const string DIAG_CMD_LINE2_KEY = "DIAG_CMD_LINE_2";

			// read in all of the sections
			IniFile ini = new IniFile(measurementDefFile);
			List<string> sections = ini.ReadAllSections();

			foreach (string section in sections)
			{
				string bsxFilePath = ini.ReadValue(section, BSX_FILE_PATH_KEY);
				string bsxFile = ini.ReadValue(section, BSX_FILE_KEY);
				string bsxCmdLine = ini.ReadValue(section, BSX_COMMAND_LINE_KEY);

				bool useDiag1 = Convert.ToBoolean(ini.ReadValue(section, USE_DIAG_CMD_LINE1_KEY));
				string diag1File = "Not Set";
				string diag1CmdLine = "Not Set";
				if (useDiag1 == true)
				{
					diag1File = ini.ReadValue(section, DIAG_FILE1_KEY);
					diag1CmdLine = ini.ReadValue(section, DIAG_CMD_LINE1_KEY);
				}

				bool useDiag2 = Convert.ToBoolean(ini.ReadValue(section, USE_DIAG_CMD_LINE2_KEY));
				string diag2File = "Not Set";
				string diag2CmdLine = "Not Set";
				if (useDiag2 == true)
				{
					diag2File = ini.ReadValue(section, DIAG_FILE2_KEY);
					diag2CmdLine = ini.ReadValue(section, DIAG_CMD_LINE2_KEY);
				}

				JtagJobInfo info = new JtagJobInfo();
				info.bsxFilePath = bsxFilePath;
				info.bsxFile = bsxFile;
				info.bsxFileCommandline = bsxCmdLine;

				info.shallWeUseDiag1 = useDiag1;
				info.diag1File = diag2File;
				info.diag1CmdLine = diag1CmdLine;

				info.shallWeUseDiag2 = useDiag2;
				info.diag2File = diag2File;
				info.diag2CmdLine = diag2CmdLine;

				_jtagMeasurements.Add(section.ToUpper(), info);
			}
		}

		#endregion

		#region PublicFuctions

		/// <summary>
		/// constructor that uses instrument manager
		/// </summary>
		/// <param name="instrumentManager"></param>
		/// <param name="instrumentName"></param>
		/// <param name="measurementDefFile"></param>
		public JtagMeasurementManager(IInstrumentManager instrumentManager, string instrumentName, string measurementDefFile = "")
		{
         _logger = LogManager.GetCurrentClassLogger();

         _jtagMeasurements = new Dictionary<string, JtagJobInfo>(StringComparer.InvariantCultureIgnoreCase);

			_jtag = instrumentManager.GetInstrument<IJtag>(instrumentName);
			_jtag?.Initialize();

			if (string.IsNullOrEmpty(measurementDefFile))
				measurementDefFile = "JtagMeasurementManager.xml";

			// parse the ini file for measurement definitions
			ParseMeasurementDef(new ConfigurationFile(measurementDefFile));
		}

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

				GC.SuppressFinalize(this);
			}
			catch (Exception err)
			{
				try
				{
					_logger?.Error(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 List<string> GetJtagMeasurementList()
		{
			return _jtagMeasurements.Keys.ToList();
			//List<string> measurements = new List<string>();
			//foreach (KeyValuePair<string, JtagJobInfo> entry in _jtagMeasurements)
			//{
			//	measurements.Add(entry.Key);
			//}
			//return measurements;
		}

		/// <summary>
		/// Perform a JTAG job
		/// </summary>
		/// <param name="jobName">The name of the job as defined in the input def file</param>
		/// <returns></returns>
		public int PerformJtagJob(string jobName)
		{
			if (_jtagMeasurements.ContainsKey(jobName.ToUpper()) == false)
			{
				throw new Exception("Could not find measurement: " + jobName);
			}

			JtagJobInfo measurement = _jtagMeasurements[jobName.ToUpper()];

			return _jtag.PerformJtagJob(measurement);
		}

		#endregion
	}
}
