//                           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 System.Text;
using NLog;
using Pickering.Pipx40.Interop;
using Raytheon.Common;

namespace Raytheon.Instruments
{
	/// <summary>
	/// A Pickering implementation of the IRelaySwitch interface
	/// </summary>
	public class SwitchPickeringPipx40 : ISwitch
	{
		#region PrivateMemberVariables
		private readonly int _handle;
		private string _name;
		private readonly int _subUnit;
		private State _state;
		private SelfTestResult _selfTestResult;

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

		#endregion

		#region PrivateFunctions

		/// <summary>
		/// Dispose of the resources contained by this object
		/// </summary>
		/// <param name="disposing"></param>
		protected virtual void Dispose(bool disposing)
		{
			try
			{
				if (disposing)
				{
					if (_state == State.Ready)
					{
						RelayOpenAll();
						Pickering.Pipx40.Interop.Pipx40Module.Reset(_handle);
						Pickering.Pipx40.Interop.Pipx40Module.Close(_handle);
						_state = State.Uninitialized;
					}
				}
			}
			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>
		/// Close a single relay
		/// The relay string should be the string form of an integer that represents the bit to close
		/// </summary>
		/// <param name="relay">The relay to close</param>
		private void RelayClose(string relay)
		{
			//VI_ON energizes
			int ret = Pickering.Pipx40.Interop.Pipx40Module.SetChannelState(_handle, _subUnit, Convert.ToInt32(relay), 1);
			//pipx40_operateSwitch
			if (ret != 0)
			{
				throw new Exception("Pickering.Pipx40.Interop.Pipx40Module.SetChannelState() return: " + ret.ToString());
			}
		}

		/// <summary>
		/// Opens a single relay
		/// The relay strings should be the string form of an integer that represents the bit to close
		/// </summary>
		/// <param name="relay">The relay to open</param>
		private void RelayOpen(string relay)
		{
			//VI_OFF energizes
			int ret = Pickering.Pipx40.Interop.Pipx40Module.SetChannelState(_handle, _subUnit, Convert.ToInt32(relay), 0);
			//pipx40_operateSwitch
			if (ret != 0)
			{
				throw new Exception("Pickering.Pipx40.Interop.Pipx40Module.SetChannelState() return: " + ret.ToString());
			}
		}

		/// <summary>
		/// Opens all relays on the card
		/// </summary>
		private void RelayOpenAll()
		{
			Pickering.Pipx40.Interop.Pipx40Module.ClearCard(_handle);

			//Pickering.Pipx40.Interop.Pipx40Module.ClearSub(_handle, _subUnit);
		}

		private void SelfTest()
		{
			SelftestFault stFault = new SelftestFault();

			StringBuilder message = new StringBuilder();

			int ret = Pickering.Pipx40.Interop.Pipx40Module.SelfTest(_handle, ref stFault, message);

			if (ret != 0)
			{
				throw new Exception("Pickering.Pipx40.Interop.Pipx40Module.SelfTest() return: " + ret.ToString() + ", " + message.ToString());
			}
		}

		#endregion

		#region PublicFunctions

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

			_logger = logger;

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

			_subUnit = _configuration.GetConfigurationValue("SwitchPickeringPipx40", "SubUnit", 0);
			
			int ret = Pipx40Module.Init(Name, 0, 1, ref _handle);
			if (ret != 0)
			{
				throw new Exception("Pickering.Pipx40.Interop.Pipx40Module.Init() return: " + ret.ToString());
			}

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

		/// <summary>
		/// 
		/// </summary>
		/// <param name="name"></param>
		/// <param name="address"></param>
		/// <param name="subUnit"></param>
		public SwitchPickeringPipx40(string name, string address, int subUnit)
		{
			_name = name;
			_logger = LogManager.GetCurrentClassLogger();
			_subUnit = subUnit;

			int ret = Pipx40Module.Init(name, 0, 1, ref _handle);
			if (ret != 0)
			{
				throw new Exception("Pickering.Pipx40.Interop.Pipx40Module.Init() return: " + ret.ToString());
			}

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

		/// <summary>
		/// The Finalizer
		/// </summary>
		~SwitchPickeringPipx40()
		{
			Dispose(false);
		}

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

		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		public void Connect(string path)
		{
			RelayClose(path);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		public void Disconnect(string path)
		{
			RelayOpen(path);
		}

		/// <summary>
		/// 
		/// </summary>
		public void DisconnectAll()
		{
			RelayOpenAll();
		}

		/// <summary>
		/// Dispose of the resources contained by this object
		/// </summary>
		public void Dispose()
		{
			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 string DetailedStatus
		{
			get
			{
				return "This is a Pickering Switch";
			}
		}

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

			set
			{
				throw new NotImplementedException();
			}
		}

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

			set
			{
				throw new NotImplementedException();
			}
		}

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

		/// <summary>
		/// 
		/// </summary>
		public void Initialize()
		{
			if (_state == State.Uninitialized)
			{
				// nothing to initialize here
				_state = State.Ready;
			}
			else
			{
				throw new Exception("expected the state to be Uninitialized, state was: " + _state.ToString());
			}
		}

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

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

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public SelfTestResult PerformSelfTest()
		{
			throw new NotImplementedException();
		}

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

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

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

		/// <summary>
		/// 
		/// </summary>
		public void Shutdown()
		{
			if (_state == State.Ready)
			{
				RelayOpenAll();
				Pickering.Pipx40.Interop.Pipx40Module.Reset(_handle);
				Pickering.Pipx40.Interop.Pipx40Module.Close(_handle);
				_state = State.Uninitialized;
			}
		}

		#endregion
	}
}
