//                           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 Pickering.Lxi.Piplx;
using Raytheon.Common;

namespace Raytheon.Instruments
{
   /// <summary>
   /// A Pickering implementation of the IRelaySwitch interface
   /// </summary>
   public class SwitchMatrixPickering40x : ISwitch
   {
      #region PrivateMemberVariables
      private string _name;
      private string _lxiIpAddress;
      private int _deviceNum;
      private int _busNum;
      private PiplxCard _switchMatrixCard;
      private State _state;
      private SelfTestResult _selfTestResult;
      private object _syncObj = new Object();
      PiplxManager _piplxManager;

      private readonly ILogger _logger;

      private readonly IConfigurationManager _configurationManager;
      private readonly IConfiguration _configuration;

      #endregion

      #region PrivateFunctions

      /// <summary>
      /// Close/open relay pair defined in the path
      /// </summary>
      /// <param name="relay">The relay to close</param>
      private void OperateRelays(string path, bool state)
      {
         lock (_syncObj)
         {
            // split path into 2 items. Each item contains channel information
            string[] channelArray = path.Split(',');

            if (channelArray.Length != 2)
            {
               throw new Exception($"Invalid path: {path}. Expected format: [subunit].[channel_x].[channel_y],[subunit].[channel_x].[channel_y]");
            }

            for (int i = 0; i < channelArray.Length; i++)
            {
               string[] itemArray = channelArray[i].Split('.');

               if (itemArray.Length != 3)
               {
                  throw new Exception($"Invalid path: {path}. Expected format: [subunit].[channel_x].[channel_y]");
               }

               int itemIndex = 0;
               if (int.TryParse(itemArray[itemIndex++], out int subUnitIndex) && int.TryParse(itemArray[itemIndex++], out int xIndex) && int.TryParse(itemArray[itemIndex++], out int yIndex))
               {
                  MatrixSubunit subUnit = (MatrixSubunit)_switchMatrixCard.Subunits[subUnitIndex];

                  subUnit.OperateCrosspoint(yIndex, xIndex, state);
               }
               else
               {
                  throw new Exception($"Invalid path: {channelArray[i]}. Expected format: [subunit].[channel_x].[channel_y]");
               }
            }
         }
      }

      /// <summary>
      /// Opens all relays on the card
      /// </summary>
      private void RelayOpenAll()
      {
         lock (_syncObj)
         {
            for (int i = 0; i < _switchMatrixCard.Subunits.Count; i++)
            {
               MatrixSubunit subUnit = (MatrixSubunit)_switchMatrixCard.Subunits[i];
               subUnit.ClearSubunit();
            }
         }
      }

      #endregion

      #region PublicFunctions

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

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

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

         _lxiIpAddress = _configuration.GetConfigurationValue(Name, "LXI_IP_ADDRESS");
         Int32.TryParse(_configuration.GetConfigurationValue(Name, "DEVICE_NUMBER"), out _deviceNum);
         Int32.TryParse(_configuration.GetConfigurationValue(Name, "BUS_NUMBER"), out _busNum);

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

      /// <summary>
      /// The Finalizer
      /// </summary>
      ~SwitchMatrixPickering40x()
      {

      }

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

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

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

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

      /// <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)
         {
            _piplxManager = new PiplxManager(_lxiIpAddress);

            foreach (PiplxCard card in _piplxManager.Cards)
            {
               PiplxCardInfo info = (PiplxCardInfo)card.Info;

               if (info.Device == _deviceNum && info.Bus == _busNum)
               {
                  _switchMatrixCard = card;

                  _switchMatrixCard.Open();

                  RelayOpenAll();

                  break;
               }
            }

            if (_switchMatrixCard == null)
            {
               throw new Exception($"No switch matrix card exists in LXI chassis with DEVICE_NUMBER={_deviceNum} and BUS_NUMBER={_busNum}");
            }

            _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)
         {
            if (_switchMatrixCard != null && _switchMatrixCard.IsOpen())
            {
               RelayOpenAll();
               _switchMatrixCard.Close();
            }

            if (_piplxManager != null && _piplxManager.Connected)
               _piplxManager.Disconnect();

            _state = State.Uninitialized;
         }
      }

      #endregion
   }
}
