//                           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 System;
using Raytheon.Instruments.GeneralIO;
using System.Collections.Generic;
using Raytheon.Common;
using NLog;
using System.IO;
using System.Reflection;
using System.Runtime.Remoting;

namespace Raytheon.Instruments
{
	/// <summary>
	/// A Simulated DIO class
	/// </summary>
	public class DIOSim : IGeneralIO
	{
		#region PrivateClassMembers
		private string _name;
		private SelfTestResult _selfTestResult;
		private State _state;
		private object _syncObj = new Object();
		/// <summary>
		/// NLog logger
		/// </summary>
		private readonly ILogger _logger;
		/// <summary>
		/// Raytheon configuration
		/// </summary>
		private readonly IConfigurationManager _configurationManager;
		private readonly IConfiguration _configuration;

      private const int _channelStartIndex = 0;
      private int _numInputChannels;
      private int _numOutputChannels;

      private Dictionary<string, IODatatypes.DIOChannelInfo> _signalNameToChannelMap = new Dictionary<string, IODatatypes.DIOChannelInfo>();

      #endregion

      #region PrivateClassFunctions

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

		/// <summary>
		/// Dispose of this object.
		/// </summary>
		/// <param name="disposing">True = currently disposing, False = not disposing.</param>
		protected virtual void Dispose(bool disposing)
		{
			try
			{
				if (disposing)
				{
					// nothing to do here
				}
			}
			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 PublicClassFunctions

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

			_logger = logger;

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

         string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
         string dioModuleDefPath = _configuration.GetConfigurationValue(deviceName, ConfigXml.DIO_MODULE_DEF_FILEPATH.ToString());

         if (!Path.IsPathRooted(dioModuleDefPath))
            dioModuleDefPath = Path.GetFullPath(Path.Combine(assemblyFolder, dioModuleDefPath));

         IConfigurationFile dioModuleConfig = new ConfigurationFile(dioModuleDefPath);

         Int32.TryParse(dioModuleConfig.ReadValue(Name, "NUM_OUTPUT_CHANNELS"), out _numOutputChannels);
         Int32.TryParse(dioModuleConfig.ReadValue(Name, "NUM_INPUT_CHANNELS"), out _numInputChannels);

         List<string> outputSignalNames = dioModuleConfig.ReadAllKeys($"{Name}.{ConfigIni.OUTPUT_SIGNALS}");
         List<string> intputSignalNames = dioModuleConfig.ReadAllKeys($"{Name}.{ConfigIni.INPUT_SIGNALS}");

         IODatatypes.DIOChannelInfo info;
         foreach (string signalName in outputSignalNames)
         {
            if (_signalNameToChannelMap.ContainsKey(signalName))
               throw new Exception($"Key {signalName} in section {Name}.{ConfigIni.OUTPUT_SIGNALS} conflicts with the same key defined in another section.");

            string iniLine = dioModuleConfig.ReadValue($"{Name}.{ConfigIni.OUTPUT_SIGNALS}", signalName);
            string[] infoTokens = iniLine.Split('|');
            if (infoTokens.Length != 2)
            {
               throw new Exception($"Key {signalName} in section {Name}.{ConfigIni.OUTPUT_SIGNALS} does not contain 2 tokens");
            }

            info.channelNumber = Convert.ToUInt32(infoTokens[0]);
            info.initialValue = Convert.ToInt32(infoTokens[1]);

            _signalNameToChannelMap[signalName] = info;
         }

         foreach (string signalName in intputSignalNames)
         {
            if (_signalNameToChannelMap.ContainsKey(signalName))
               throw new Exception($"Key {signalName} in section {Name}.{ConfigIni.INPUT_SIGNALS} conflicts with the same key defined in another section.");

            string iniLine = dioModuleConfig.ReadValue($"{Name}.{ConfigIni.INPUT_SIGNALS}", signalName);

            info.channelNumber = Convert.ToUInt32(iniLine);
            info.initialValue = -1;

            _signalNameToChannelMap[signalName] = info;
         }

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

		/// <summary>
		/// Constructor for DIO simulation.
		/// </summary>
		/// <param name="name"></param>
		/// <param name="inputPins"></param>
		/// <param name="outputPins"></param>
		public DIOSim(string name)
		{
			_name = name;
			_logger = LogManager.GetCurrentClassLogger();
			_selfTestResult = SelfTestResult.Unknown;
			_state = State.Uninitialized;
		}

      /// <summary>
      /// Return list of signal names
      /// </summary>
      public List<string> GetSignalNames()
      {
         return new List<string>(_signalNameToChannelMap.Keys);
      }

      /// <summary>
      /// 
      /// </summary>
      /// <returns></returns>
      public bool ClearErrors()
		{
			throw new NotImplementedException();
		}

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

		/// <summary>
		/// 
		/// </summary>
		public bool DisplayEnabled
		{
			get
			{
				throw new NotImplementedException();
			}

			set
			{
				throw new NotImplementedException();
			}
		}

		/// <summary>
		/// Dispose of this object.
		/// </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
			{
				throw new NotImplementedException();
			}

			set
			{
				throw new NotImplementedException();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="bit"></param>
		/// <returns></returns>
		public IODatatypes.BitState GetBitState(string signalName)
		{
			lock (_syncObj)
			{
				if (!_signalNameToChannelMap.ContainsKey(signalName))
					throw new Exception($"Signal name {signalName} doesn't exist for card: " + _name);

            if (_signalNameToChannelMap[signalName].channelNumber >= _numInputChannels || _signalNameToChannelMap[signalName].channelNumber < _channelStartIndex)
            {
               throw new Exception($"The input channel number {_signalNameToChannelMap[signalName].channelNumber} specified must be >= {_channelStartIndex} and < {_numInputChannels} on card " + _name);
            }

            return IODatatypes.BitState.Low;
			}
		}

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

		/// <summary>
		/// 
		/// </summary>
		public void Initialize()
		{
			lock (_syncObj)
			{
				if (_state == State.Uninitialized)
				{
					_state = State.Ready;
				}
				else
				{
					throw new Exception("DIOSim::Initialize() - 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>
		public uint NumberOfInputBits
		{
			get
			{
				return (uint)_numInputChannels;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public uint NumberOfOutputBits
		{
			get
			{
				return (uint)_numOutputChannels;
			}
		}

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

		/// <summary>
		/// 
		/// </summary>
		public void Reset()
		{
			lock (_syncObj)
			{
			}
		}

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

      /// <summary>
      /// 
      /// </summary>
      /// <param name="channelNum"></param>
      /// <param name="state"></param>
      public void SetBit(string signalName, IODatatypes.BitState state)
		{
			lock (_syncObj)
			{
            if (!_signalNameToChannelMap.ContainsKey(signalName))
               throw new Exception($"Signal name {signalName} doesn't exist for card: " + _name);

            if (_signalNameToChannelMap[signalName].channelNumber >= _numOutputChannels || _signalNameToChannelMap[signalName].channelNumber < _channelStartIndex)
            {
               throw new Exception($"The input channel number {_signalNameToChannelMap[signalName].channelNumber} specified must be >= {_channelStartIndex} and < {_numOutputChannels} on card " + _name);
            }
         }
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="bit"></param>
		public void SetTristate(string signalName)
		{

		}

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

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