//                           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 NationalInstruments.ModularInstruments.NISwitch;
using NLog;
using Raytheon.Common;

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

      private NISwitch _niSwitch;
      private string _name;
      private readonly string _address;
      private readonly string _topology;
      private State _state;
      private SelfTestResult _selfTestResult;

      private readonly ILogger _logger;

      private readonly IConfigurationManager _configurationManager;
      private readonly IConfiguration _configuration;

      #endregion

      #region PrivateFunctions

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

      /// <summary>
      /// Dispose of this object's resources.
      /// </summary>
      /// <param name="disposing">True = currently disposing, False = not disposing.</param>
      protected virtual void Dispose(bool disposing)
      {
         if (disposing)
         {
            if (_state == State.Ready)
            {
               _niSwitch.Utility.Reset();

               _niSwitch.Close();

               _niSwitch.Dispose();

               _state = State.Uninitialized;
            }
         }
      }

      #endregion

      #region PublicFunctions

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

         _logger = LogManager.GetLogger($"{this.GetType().Name} - {deviceName}");

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

         _address = _configuration.GetConfigurationValue("SwitchNiPxi", "Address", "");
         _topology = _configuration.GetConfigurationValue("SwitchNiPxi", "Topology", "");

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

      /// <summary>
      /// 
      /// </summary>
      /// <param name="deviceName"></param>
      /// <param name="address"></param>
      public SwitchNiPxi(string deviceName, string address, string topology = "")
      {
         _name = deviceName;
         _logger = LogManager.GetLogger($"{this.GetType().Name} - {deviceName}");
         _address = address;
         _topology = topology;

         // set in Initialize()
         _niSwitch = null;

         _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)
      {
         _niSwitch.RelayOperations.RelayControl(path, SwitchRelayAction.CloseRelay);
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="path"></param>
      public void Disconnect(string path)
      {
         _niSwitch.RelayOperations.RelayControl(path, SwitchRelayAction.OpenRelay);
      }

      /// <summary>
      /// 
      /// </summary>
      public void DisconnectAll()
      {
         _niSwitch.Path.DisconnectAll();
      }

      /// <summary>
      /// Dispose of this object.
      /// </summary>
      public void Dispose()
      {
         Dispose(true);

         GC.SuppressFinalize(this);
      }

      /// <summary>
      /// 
      /// </summary>
      public string DetailedStatus
      {
         get
         {
            return "This is a NI 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 bool IsDebounced
      {
         get
         {
            throw new NotImplementedException();
         }
      }

      /// <summary>
      /// 
      /// </summary>
      public void Initialize()
      {
         if (_state == State.Uninitialized)
         {
            _niSwitch = new NISwitch(_address, _topology, false, true);

            //_niSwitch.ModuleCharacteristics.PowerDownLatchingRelaysAfterDebounce

            _state = State.Ready;
         }
         else
         {
            throw new Exception("expected the state to be Uninitialized, state was: " + _state.ToString());
         }
      }

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

      /// <summary>
      /// 
      /// </summary>
      /// <returns></returns>
      public SelfTestResult PerformSelfTest()
      {
         Ivi.Driver.SelfTestResult res = _niSwitch.Utility.SelfTest();

         if (res.Code != 0)
         {
            _selfTestResult = Raytheon.Instruments.SelfTestResult.Fail;
            throw new Exception("self test returned: " + res.Code + "," + res.Message + " on card " + _name);
         }

         _selfTestResult = Raytheon.Instruments.SelfTestResult.Pass;

         return _selfTestResult;
      }

      /// <summary>
      /// 
      /// </summary>
      public void Reset()
      {
         _niSwitch.Utility.Reset();
      }

      /// <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)
         {
            _niSwitch.Utility.Reset();

            _niSwitch.Close();

            _niSwitch.Dispose();

            _state = State.Uninitialized;
         }
      }

      #endregion
   }
}
