//                           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.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using FpgaMeasurementInstrumentsLib;
using NLog;
using Raytheon.Common;

namespace Raytheon.Instruments
{
   /// <summary>
   /// A class that implements the Teradyne HSS Test Station Chassis
   /// </summary>
   public unsafe class CommFpgaHssubChassisTs : IFpgaComm
   {
      #region PrivateClassMembers
      public struct LocalBusParams
      {
         public int cardHandle;
         public int address;
         public int data;
      }

      public struct CardInfo
      {
         public string cardName;
         public string cardAddress;
         public int startingOffset;
         public string cardFirmwareFile;
         public string memMap;
      }

      private static object _syncObj = new Object();

      private SortedDictionary<string, CommFpgaHssubCardTs> _hssCardNameMap;
      private SortedDictionary<int, CommFpgaHssubCardTs> _hssCardHandleMap;

      private readonly string _chassisAddress;
      private readonly string _killHandlerAppName;
      private readonly string _msgHandlerAppName;
      private uint _chassisHandle;
      private int _hssubAppInit;
      private int _hssubSubSystemApp;
      private int _hssubSubSystemAppSync;
      private int _hssubCloseAppSync;
      private int _hssubKillApp;
      private int _hsiHandle;
      private List<CardInfo> _cardList;
      private SelfTestResult _selfTestResult;
      private State _state;
      private string _name;

      private HssubNativeMethods.MessageCallbackDelagate _callBack;

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

      #endregion

      #region PrivateFuctions

      /// <summary>
      /// The finalizer.
      /// </summary>
      ~CommFpgaHssubChassisTs()
      {
         Dispose(false);
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="cardName"></param>
      /// <param name="cardAddress"></param>
      /// <param name="cardOffset"></param>
      /// <param name="cardFirmwareFile"></param>
      private void CreateCard(string cardName, string cardAddress, int startingOffset, string cardFirmwareFile, string memMap)
      {
         lock (_syncObj)
         {
            // create the card
            CommFpgaHssubCardTs card = new CommFpgaHssubCardTs(cardName, cardAddress, startingOffset, cardFirmwareFile, _chassisHandle, _hssubSubSystemApp, _hssubSubSystemAppSync, memMap);

            // wait for the chassis to respond
            HssUtilTs.WaitForSync(_chassisHandle, _hssubSubSystemAppSync, _name);

            // make sure the chassis gave us a good card handle
            if (_hsiHandle == 0)
            {
               throw new Exception("_hsiHandle is 0");
            }

            // give the card its handle
            card.SetHandle(_hsiHandle);

            // hold onto the card
            _hssCardNameMap[cardName] = card;
            _hssCardHandleMap[_hsiHandle] = card;

            // set the _hsiHandle back to zero for the next card
            _hsiHandle = 0;
         }
      }

      /// <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)
         {
            lock (_syncObj)
            {
               if (_state == State.Ready)
               {
                  int ret = HssubNativeMethods.terHss_close(_chassisHandle);

                  _state = State.Uninitialized;
               }
            }
         }
      }

      /// <summary>
      /// 
      /// </summary>
      private void InitChassis()
      {
         //0 is VI_FALSE, 1 is VI_TRUE
         int ret = HssubNativeMethods.terHss_init(_chassisAddress, 0, 1, ref _chassisHandle);

         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_init returned returned an error(" + ret + ")" + ": " + errorStr);
         }

         // start the message application
         LoadMessageApp();
      }

      /// <summary>
      /// 
      /// </summary>
      private void LoadMessageApp()
      {
         int ret = HssubNativeMethods.terHss_Application_CreateSyncObject(_chassisHandle, "AppInit", ref _hssubAppInit);
         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_Application_CreateSyncObject(AppInit) returned an error(" + ret + ")" + ": " + errorStr);
         }

         ret = HssubNativeMethods.terHss_Application_CreateSyncObject(_chassisHandle, "AppSync", ref _hssubSubSystemAppSync);
         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_Application_CreateSyncObject(AppSync) returned an error(" + ret + ")" + ": " + errorStr);
         }

         ret = HssubNativeMethods.terHss_Application_CreateSyncObject(_chassisHandle, "SubAppQuit", ref _hssubCloseAppSync);
         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_Application_CreateSyncObject(SubAppQuit) returned an error(" + ret + ")" + ": " + errorStr);
         }

         ret = HssubNativeMethods.terHss_Application_RegisterMessageCallback(_chassisHandle, _callBack);
         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_Application_RegisterMessageCallback() returned an error(" + ret + ")" + ": " + errorStr);
         }

         ret = HssubNativeMethods.terHss_Subsystem_SendFile(_chassisHandle, _killHandlerAppName, "c:\\temp\\killhndlr.bat", HssubNativeMethods.TERHSS_OPTION_ALLOW_OVERWRITE);
         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_SubSyste_SendFile(Killer App) returned an error(" + ret + ")" + ": " + errorStr);
         }

         ret = HssubNativeMethods.terHss_Application_Load(_chassisHandle, "Killer App", "c:\\temp\\killhndlr.bat", ref _hssubKillApp);
         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_Application_Load(Killer App) returned an error(" + ret + ")" + ": " + errorStr);
         }

         ret = HssubNativeMethods.terHss_Application_Start(_chassisHandle, _hssubKillApp, "", 1);
         /*if (ret != 0)
			{
			   string errorStr = HssUtil.BuildErrorString(_chassisHandle, ret, _chassisLogicalName);

			   throw new Exception("terHss_Application_Start(Killer App) returned an error(" + ret + ")" + ": " + errorStr);
			}*/

         ret = HssubNativeMethods.terHss_Subsystem_SendFile(_chassisHandle, _msgHandlerAppName, "c:\\temp\\hndlr.exe", HssubNativeMethods.TERHSS_OPTION_ALLOW_OVERWRITE);
         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_SubSyste_SendFile(Msg Handler App) returned an error(" + ret + ")" + ": " + errorStr);
         }

         ret = HssubNativeMethods.terHss_Application_Load(_chassisHandle, "Subsystem App", "c:\\temp\\hndlr.exe", ref _hssubSubSystemApp);
         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_Application_Load(Msg Handler App) returned an error(" + ret + ")" + ": " + errorStr);
         }

         ret = HssubNativeMethods.terHss_Application_Start(_chassisHandle, _hssubSubSystemApp, "", HssubNativeMethods.TERHSS_TIMEOUT_60SEC);
         if (ret != 0)
         {
            string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

            throw new Exception("terHss_Application_Start(Msg Handler App) returned an error(" + ret + ")" + ": " + errorStr);
         }

         // wait for the chassis to respond
         HssUtilTs.WaitForSync(_chassisHandle, _hssubAppInit, _name);
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="sessionHandle"></param>
      /// <param name="applicationHandle"></param>
      /// <param name="messageContext"></param>
      /// <param name="messageSize"></param>
      /// <param name="message"></param>
      private void MessageCallback(uint sessionHandle, int applicationHandle, int messageContext, uint messageSize, byte* pMessage)
      {
         try
         {
            if (messageContext == HssubNativeMethods.MESSAGE_CONTEXT_INIT_INSTRUMENT)
            {
               int* pTemp = (int*)pMessage;
               _hsiHandle = *pTemp;
            }
            else if (messageContext == HssubNativeMethods.MESSAGE_CONTEXT_LB_READ32)
            {
               // get data into array and convert to the LocalBusParams structure
               byte[] arr = new byte[messageSize];

               Marshal.Copy((IntPtr)pMessage, arr, 0, (int)messageSize);

               HssUtilTs.LocalBusParams lbParams = HssUtilTs.ByteArrayToLocalBusParms(arr);

               _hssCardHandleMap[lbParams.cardHandle].SetLocalBusRxData(lbParams.address, lbParams.data);
            }
         }
         catch { }
      }

      #endregion

      #region PublicFuctions

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

         _logger = logger;

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

         _chassisAddress = _configuration.GetConfigurationValue("CommFpgaHssubChassisTs", "ChassisAddress", "127.0.0.1");
         _killHandlerAppName = _configuration.GetConfigurationValue("CommFpgaHssubChassisTs", "KillHandlerAppName", "");
         _msgHandlerAppName = _configuration.GetConfigurationValue("CommFpgaHssubChassisTs", "MsgHandlerAppName", "");

         _cardList = new List<CardInfo>();

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

         // hold onto callback
         _callBack = new HssubNativeMethods.MessageCallbackDelagate(MessageCallback);

         // _chassisHandle gets set in Initialize
         _chassisHandle = 0;

         // these get initialized in LoadMessageApp()
         _hssubAppInit = 0;
         _hssubSubSystemApp = 0;
         _hssubSubSystemAppSync = 0;
         _hssubCloseAppSync = 0;
         _hssubKillApp = 0;

         // this is for card handles, it gets set in the MessageCallback() and passed over to the card object
         _hsiHandle = 0;

         // hold onto the card objects
         _hssCardNameMap = new SortedDictionary<string, CommFpgaHssubCardTs>();
         _hssCardHandleMap = new SortedDictionary<int, CommFpgaHssubCardTs>();
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="chassisLogicalName"></param>
      /// <param name="chassisAddress"></param>
      /// <param name="killHandlerAppName"></param>
      /// <param name="msgHandlerAppName"></param>
      public CommFpgaHssubChassisTs(string name, string chassisAddress, string killHandlerAppName, string msgHandlerAppName)
      {
         // hang onto passed in args
         _name = name;
         _logger = LogManager.GetCurrentClassLogger();
         _chassisAddress = chassisAddress;
         _killHandlerAppName = killHandlerAppName;
         _msgHandlerAppName = msgHandlerAppName;
         _cardList = new List<CardInfo>();

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

         // hold onto callback
         _callBack = new HssubNativeMethods.MessageCallbackDelagate(MessageCallback);

         // _chassisHandle gets set in Initialize
         _chassisHandle = 0;

         // these get initialized in LoadMessageApp()
         _hssubAppInit = 0;
         _hssubSubSystemApp = 0;
         _hssubSubSystemAppSync = 0;
         _hssubCloseAppSync = 0;
         _hssubKillApp = 0;

         // this is for card handles, it gets set in the MessageCallback() and passed over to the card object
         _hsiHandle = 0;

         // hold onto the card objects
         _hssCardNameMap = new SortedDictionary<string, CommFpgaHssubCardTs>();
         _hssCardHandleMap = new SortedDictionary<int, CommFpgaHssubCardTs>();
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="cardInfo"></param>
      public void AddCard(CardInfo cardInfo)
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            _cardList.Add(cardInfo);
         }
      }

      /// <summary>
      /// 
      /// </summary>
      /// <returns></returns>
      public bool ClearErrors()
      {
         return false;
      }

      /// <summary>
      /// 
      /// </summary>
      public string DetailedStatus
      {
         get
         {
            return "This is a FPGA HSS TS called " + _name;
         }
      }

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

      /// <summary>
      /// Dispose of this object's resources.
      /// </summary>
      public void Dispose()
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            Dispose(true);

            GC.SuppressFinalize(this);
         }
      }

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

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

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

      /// <summary>
      /// 
      /// </summary>
      /// <param name="fpga"></param>
      public void Initialize(string fpga)
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            if (_state == State.Uninitialized)
            {
               InitChassis();

               // init each card
               for (int i = 0; i < _cardList.Count; i++)
               {
                  CreateCard(_cardList[i].cardName, _cardList[i].cardAddress, _cardList[i].startingOffset, _cardList[i].cardFirmwareFile, _cardList[i].memMap);
               }

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

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

      /// <summary>
      /// 
      /// </summary>
      /// <returns></returns>
      public SelfTestResult PerformSelfTest()
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            short testResults = -1;

            StringBuilder errorStrTemp = new StringBuilder(512);

            int ret = HssubNativeMethods.terHss_self_test(_chassisHandle, ref testResults, errorStrTemp);

            if (ret != 0)
            {
               string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);

               throw new Exception("terHss_self_test returned an error(" + ret + ")" + ": " + errorStr);
            }
            else if (testResults != 0)
            {
               _selfTestResult = SelfTestResult.Fail;
               throw new Exception("HSSub Self Test returned an error: " + testResults.ToString() + ": " + errorStrTemp.ToString());
            }
            else
            {
               _selfTestResult = SelfTestResult.Pass;
            }

            return _selfTestResult;
         }
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="fpgaName"></param>
      /// <param name="address"></param>
      /// <returns></returns>
      public uint Read(string fpgaName, uint address)
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            return _hssCardNameMap[fpgaName].Read(fpgaName, address);
         }
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="fpgaName"></param>
      /// <param name="address"></param>
      /// <param name="numberOfWordsToRead"></param>
      /// <param name="shallWeIncrementAddress"></param>
      /// <param name="dataRead"></param>
      public void ReadBlock(string fpgaName, uint address, uint numberOfWordsToRead, bool shallWeIncrementAddress, ref uint[] dataRead)
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            _hssCardNameMap[fpgaName].ReadBlock(fpgaName, address, numberOfWordsToRead, shallWeIncrementAddress, ref dataRead);
         }
      }

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

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

      /// <summary>
      /// 
      /// </summary>
      public void Shutdown()
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            if (_state == State.Ready)
            {
               int ret = HssubNativeMethods.terHss_close(_chassisHandle);

               _state = State.Uninitialized;
            }
         }
      }

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

      /// <summary>
      /// 
      /// </summary>
      /// <param name="fpgaName"></param>
      /// <param name="address"></param>
      /// <param name="value"></param>
      public void Write(string fpgaName, uint address, uint value)
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            _hssCardNameMap[fpgaName].Write(fpgaName, address, value);
         }
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="fpgaName"></param>
      /// <param name="address"></param>
      /// <param name="numberOfWordsToWrite"></param>
      /// <param name="data"></param>
      /// <param name="shallWeIncrementAddress"></param>
      public void WriteBlock(string fpgaName, uint address, uint numberOfWordsToWrite, uint[] data, bool shallWeIncrementAddress)
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            _hssCardNameMap[fpgaName].WriteBlock(fpgaName, address, numberOfWordsToWrite, data, shallWeIncrementAddress);
         }
      }

      /// <summary>
      /// Loads firmware
      /// </summary>
      /// <param name="fpgaName"></param>
      public void LoadFirmware(string fpgaName)
      {
         Initialize(fpgaName);
      }

      #endregion
   }
}
