//                           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 SwitchMultiplexerPickering60x : ISwitch
   {
      enum SubUnit
      {
         HiMux,
         LoMux,
         Switch,
         Matrix
      }

      #region PrivateMemberVariables
      private string _name;
      private string _lxiIpAddress;
      private bool _isSingleCardMode;
      private int _cardNumWithConnectedDmm;
      private int _cardStartingIndex = 0;
      private int _virtualCardCount = 1;
      private int _numBusSelectPerCard = 0;
      // Only used to route a closed channel from one card to another card that is connected to DMM to make measurement
      // There's no use case for us to be switching between the bus select channels, so we pick one channel to route signals from one card to another
      static private int _busSelectMatrixChanNum = 1;
      private State _state;
      private SelfTestResult _selfTestResult;
      private object _syncObj = new Object();
      private 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 open</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: [Card_Index].[Switch_Chan_Num],[Card_Index].[Switch_Chan_Num]");
            }

            string channelInfo;
            int hiChannelNum = 0;
            int loChannelNum = 0;
            int hiCardNum = 0;
            int loCardNum = 0;
            for (int i = 0; i < channelArray.Length; i++)
            {
               channelInfo = channelArray[i].Trim();

               string[] itemArray = channelInfo.Split('.');

               int itemIndex = 0;
               if (int.TryParse(itemArray[itemIndex++], out int cardIndex) && int.TryParse(itemArray[itemIndex++], out int channelNum))
               {
                  if (_isSingleCardMode)
                  {
                     if (cardIndex != _cardStartingIndex)
                        throw new Exception($"Invalid card index: {cardIndex}. Card index can only be 0 when operating in single card mode");
                  }
                  else if (cardIndex < _cardStartingIndex || cardIndex >= _piplxManager.CardsCount)
                  {
                     throw new Exception($"Invalid card index: {cardIndex}. Card index can only be between {_cardStartingIndex} and {_piplxManager.CardsCount - 1} when operating in individual card mode");
                  }

                  // close/open the channel relay
                  GetSwitchSubUnit(cardIndex).OperateBit(channelNum, state);

                  if (i == 0)
                  {
                     // close/open Hi mux relay
                     GetHiMuxSubUnit(cardIndex).OperateBit(channelNum, state);
                     hiCardNum = cardIndex;
                     hiChannelNum = channelNum;
                  }
                  else
                  {
                     // close/open Lo mux relay
                     GetLoMuxSubUnit(cardIndex).OperateBit(channelNum, state);
                     loCardNum = cardIndex;
                     loChannelNum = channelNum;
                  }
               }
               else
               {
                  throw new Exception($"Invalid channel information: {channelInfo}. Expected format: [Card_Index].[Switch_Chan_Num]");
               }
            }

            if (hiChannelNum > 0 && loChannelNum > 0)
            {
               if (_isSingleCardMode)
               {
                  // calculate physical number of switching channels per physical card
                  int phyNumChanPerCard = GetSwitchSubUnit(_cardStartingIndex).BitsCount / (_piplxManager.CardsCount - 1);

                  // calculate physical card number for Hi side
                  int phyHiCardNum = (int)Math.Ceiling((double)hiChannelNum / (double)phyNumChanPerCard);

                  // calculate physical card number for Lo side
                  int phyLoCardNum = (int)Math.Ceiling((double)loChannelNum / (double)phyNumChanPerCard);

                  if (phyHiCardNum != _cardNumWithConnectedDmm)
                  {
                     // calculate virtual bus select matrix channel on the card that is being switched
                     int virtualBusSelectMatrixChanNum = (phyHiCardNum * _numBusSelectPerCard) + (_busSelectMatrixChanNum - _numBusSelectPerCard);

                     // open/close the bus select channel so we can route the Hi channel from this card to the card connected to the DMM
                     GetMatrixSubUnit(_cardStartingIndex).OperateCrosspoint(1, virtualBusSelectMatrixChanNum, state);
                  }

                  if (phyLoCardNum != _cardNumWithConnectedDmm)
                  {
                     // calculate virtual bus select matrix channel on the card that is being switched
                     int virtualBusSelectMatrixChanNum = (phyLoCardNum * _numBusSelectPerCard) + (_busSelectMatrixChanNum - _numBusSelectPerCard);

                     // open/close the bus select channel so we can route the Lo channel from this card to the card connected to the DMM
                     GetMatrixSubUnit(_cardStartingIndex).OperateCrosspoint(2, virtualBusSelectMatrixChanNum, state);
                  }
               }
               else if (hiCardNum > 0 && loCardNum > 0)
               {
                  if (hiCardNum != _cardNumWithConnectedDmm)
                  {
                     // open/close the bus select channel so we can route the Hi channel from this card to the card connected to the DMM
                     GetMatrixSubUnit(hiCardNum).OperateCrosspoint(1, _busSelectMatrixChanNum, state);
                  }

                  if (loCardNum != _cardNumWithConnectedDmm)
                  {
                     // open/close the bus select channel so we can route the Lo channel from this card to the card connected to the DMM
                     GetMatrixSubUnit(loCardNum).OperateCrosspoint(2, _busSelectMatrixChanNum, state);
                  }
               }
            }
         }
      }

      /// <summary>
      /// Opens all relays on the card
      /// </summary>
      private void RelayOpenAll()
      {
         lock (_syncObj)
         {
            for (int i = _cardStartingIndex; i < _virtualCardCount; i++)
            {
               if (_piplxManager.Cards[i].IsOpen())
               {
                  GetHiMuxSubUnit(i).ClearSubunit();
                  GetLoMuxSubUnit(i).ClearSubunit();
                  GetSwitchSubUnit(i).ClearSubunit();
                  GetMatrixSubUnit(i).ClearSubunit();
               }
            }
         }
      }

      /// <summary>
      /// Get Hi Mux Sub Unit
      /// </summary>
      private MultiplexerSubunit GetHiMuxSubUnit(int cardIndex)
      {
         return (MultiplexerSubunit)((PiplxCard)_piplxManager.Cards[cardIndex]).OutputSubunits[(int)SubUnit.HiMux];
      }

      /// <summary>
      /// Get Low Mux Sub Unit
      /// </summary>
      private MultiplexerSubunit GetLoMuxSubUnit(int cardIndex)
      {
         return (MultiplexerSubunit)((PiplxCard)_piplxManager.Cards[cardIndex]).OutputSubunits[(int)SubUnit.LoMux];
      }

      /// <summary>
      /// Get Switch Sub Unit
      /// </summary>
      private SwitchSubunit GetSwitchSubUnit(int cardIndex)
      {
         return (SwitchSubunit)((PiplxCard)_piplxManager.Cards[cardIndex]).OutputSubunits[(int)SubUnit.Switch];
      }

      /// <summary>
      /// Get Matrix Sub Unit
      /// </summary>
      private MatrixSubunit GetMatrixSubUnit(int cardIndex)
      {
         return (MatrixSubunit)((PiplxCard)_piplxManager.Cards[cardIndex]).OutputSubunits[(int)SubUnit.Matrix];
      }

      #endregion

      #region PublicFunctions

      /// <summary>
      /// SwitchMultiplexerPickering60x factory constructor
      /// </summary>
      /// <param name="deviceName"></param>
      /// <param name="configurationManager"></param>
      public SwitchMultiplexerPickering60x(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");
         bool.TryParse(_configuration.GetConfigurationValue(Name, "IS_SINGLE_CARD_MODE"), out _isSingleCardMode);
         Int32.TryParse(_configuration.GetConfigurationValue(Name, "CARD_NUMBER_WITH_CONNECTED_DMM"), out _cardNumWithConnectedDmm);
         Int32.TryParse(_configuration.GetConfigurationValue(Name, "BUS_SELECT_MATRIX_CHANNEL_NUMBER"), out _busSelectMatrixChanNum);

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

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

      }

      /// <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);

            if (!_isSingleCardMode)
            {
               _cardStartingIndex = 1;
               _virtualCardCount = _piplxManager.CardsCount;
               _numBusSelectPerCard = GetMatrixSubUnit(_cardStartingIndex).BitsCount;
            }
            else
            {
               // calculate number of bus select channels per card
               _numBusSelectPerCard = (GetMatrixSubUnit(_cardStartingIndex).BitsCount / (_piplxManager.CardsCount - 1)) / 2;
            }

            if (_busSelectMatrixChanNum < 1 || _busSelectMatrixChanNum > _numBusSelectPerCard)
            {
               throw new Exception($"Invalid bus select channel: {_busSelectMatrixChanNum}. Number must be between 1 and {_numBusSelectPerCard}");
            }

            if (_cardNumWithConnectedDmm < 1 || _cardNumWithConnectedDmm >= _piplxManager.CardsCount)
            {
               throw new Exception($"Invalid card number: {_cardNumWithConnectedDmm} for the card that is connected to DMM. Number must be between 1 and {_piplxManager.CardsCount - 1}");
            }

            for (int i = _cardStartingIndex; i < _virtualCardCount; i++)
            {
               _piplxManager.Cards[i].Open();

               GetHiMuxSubUnit(i).ClearSubunit();
               GetLoMuxSubUnit(i).ClearSubunit();
               GetSwitchSubUnit(i).ClearSubunit();
               GetMatrixSubUnit(i).ClearSubunit();
            }

            if (_isSingleCardMode)
            {
               // calculate virtual bus select matrix channel on the card that's connected to the DMM
               int virtualBusSelectMatrixChanNum = (_cardNumWithConnectedDmm * _numBusSelectPerCard) + (_busSelectMatrixChanNum - _numBusSelectPerCard);

               // close the bus select relay on the card that is connected to DMM
               // so we can route channels on other cards to this card in order to make DMM measurements
               // close the Hi channel
               GetMatrixSubUnit(_cardStartingIndex).OperateCrosspoint(1, virtualBusSelectMatrixChanNum, true);
               // close the Lo channel
               GetMatrixSubUnit(_cardStartingIndex).OperateCrosspoint(2, virtualBusSelectMatrixChanNum, true);
            }
            else
            {
               // close the bus select relay on the card that is connected to DMM
               // so we can route channels on other cards to this card in order to make DMM measurements
               // close the Hi channel
               GetMatrixSubUnit(_cardNumWithConnectedDmm).OperateCrosspoint(1, _busSelectMatrixChanNum, true);
               // close the Lo channel
               GetMatrixSubUnit(_cardNumWithConnectedDmm).OperateCrosspoint(2, _busSelectMatrixChanNum, true);
            }

            _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();

            for (int i = _cardStartingIndex; i < _virtualCardCount; i++)
            {
               if (_piplxManager.Cards[i].IsOpen())
               {
                  _piplxManager.Cards[i].Close();
               }
            }

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

            _state = State.Uninitialized;
         }
      }

      #endregion
   }
}
