//                           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 NLog;
using Raytheon.Common;
using SwitchMeasurementInstrumentsLib.Pickering40LxiSoap;

namespace Raytheon.Instruments
{
	/// <summary>
	/// A Pickering implementation of the IRelaySwitch interface
	/// </summary>
	public class SwitchPickeringLxi40_531_Soap : ISwitch, IDisposable
	{
		#region PrivateMemberVariables

		private string _name;
		private PiCards _card;
		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>
		/// The Finalizer
		/// </summary>
		~SwitchPickeringLxi40_531_Soap()
		{
			Dispose(false);
		}

		/// <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)
					{
						_card.ClearAll();
						_card.Dispose();
						_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)
		{
			int ret = _card.OpBit(_subUnit, Convert.ToInt32(relay), true);

			if (ret != 0)
			{
				throw new Exception("OpBit failed with a ret of: " + ret);
			}
		}

		/// <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)
		{
			int ret = _card.OpBit(_subUnit, Convert.ToInt32(relay), false);

			if (ret != 0)
			{
				throw new Exception("OpBit failed with a ret of: " + ret);
			}
		}

		/// <summary>
		/// Opens all relays on the card
		/// </summary>
		private void RelayOpenAll()
		{
			int ret = _card.ClearCard();

			if (ret != 0)
			{
				throw new Exception("OpBit failed with a ret of: " + ret);
			}
		}

		#endregion

		#region PublicFunctions

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

			_logger = logger;

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

			var address = _configuration.GetConfigurationValue("SwitchPickeringLxi60_522_Soap", "Address", "127.0.0.1");
			var deviceNumber = _configuration.GetConfigurationValue<long>("SwitchPickeringLxi60_522_Soap", "DeviceNumber", 0);
			var busNumber = _configuration.GetConfigurationValue<long>("SwitchPickeringLxi60_522_Soap", "BusNumber", 0);

			_subUnit = _configuration.GetConfigurationValue("SwitchPickeringLxi60_522_Soap", "SubUnit", 0);

			_card = new PiCards
			{
				Url = $"http://{address}/bin/picards"
			};

			LocationHeader lh = new LocationHeader
			{
				Slot = deviceNumber,
				Bus = busNumber
			};

			_card.CardLocation = lh;

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

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

			_subUnit = subUnit;

			_card = new PiCards();

			string tempAddress = "http://" + address + "/bin/picards";
			_card.Url = tempAddress;

			LocationHeader lh = new LocationHeader();
			lh.Slot = deviceNumber;
			lh.Bus = busNumber;

			_card.CardLocation = lh;

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

		/// <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)
			{
				_card.ClearAll();
				_card.Dispose();
				_state = State.Uninitialized;
			}
		}

		#endregion
	}
}
