//                           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.IO.Ports;
using System.Threading;
using NLog;
using Raytheon.Common;

namespace Raytheon.Instruments
{
   /// <summary>
   /// A class the provides an interface for read/write to registers on an FPGA that implement PC Node communication
   /// </summary>
   public class CommFpgaPcNode2x : IFpgaComm, IDisposable
   {
      #region PrivateClassMembers
      private SerialPort _serialPort;
      private readonly uint _pcNodeAddress;
      private byte[] _readBuf;
      private static object _syncObj = new Object();
      private uint _delayBeforeReadMs;
      private SelfTestResult _selfTestResult;
      private State _state;
      private string _name;

      private readonly ILogger _logger;

      private readonly IConfigurationManager _configurationManager;
      private readonly IConfiguration _configuration;

      #endregion

      #region PrivateFuctions

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

      /// <summary>
      /// Builds a command in the PC node format
      /// </summary>
      /// <param name="address">The address to write to</param>
      /// <param name="data">The data to write</param>
      /// <param name="isForRead">True is the command is to perform a read, false to perform a write</param>
      /// <returns>The formatted command</returns>
      private byte[] BuildCommand(uint address, uint data, bool isForRead)
      {
         byte[] command = new byte[9];

         byte type = 0;

         // 2 bit shift per the spec, regardless of its a read or write
         address = address >> 2;

         if (isForRead == true)
         {
            type = 0xf1;

            // 2 bit shift per the spec for the read (this would be the PC node address)
            data = data >> 2;
         }
         else
         {
            type = 0xf0;
         }

         command[0] = type;
         byte[] addressBytes = BitConverter.GetBytes(address);
         Array.Copy(addressBytes, 0, command, 1, addressBytes.Length);

         byte[] dataBytes = BitConverter.GetBytes(data);
         Array.Copy(dataBytes, 0, command, 5, dataBytes.Length);

         return command;
      }

      /// <summary>
      /// Reads the serial port until it is empty
      /// </summary>
      private void ClearBuffer()
      {
         lock (_syncObj)
         {
            bool isClearComplete = false;

            while (isClearComplete == false)
            {
               try
               {
                  int numBytesRead = _serialPort.Read(_readBuf, 0, _readBuf.Length);

                  if (numBytesRead < _readBuf.Length)
                  {
                     isClearComplete = true;
                  }
               }
               catch (Exception)
               {
                  //expected if buffer is already cleared
                  isClearComplete = true;
               }
            }
         }
      }

      /// <summary>
      /// Dispose of this object
      /// </summary>
      /// <param name="disposing"></param>
      protected virtual void Dispose(bool disposing)
      {
         if (disposing)
         {
            if (_state == State.Ready)
            {
               _serialPort.Dispose();

               _state = State.Uninitialized;
            }
         }
      }

      #endregion

      #region PublicFuctions

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

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

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

         _pcNodeAddress = _configuration.GetConfigurationValue<uint>("CommFpgaPcNode2x", "PCNodeAddress", 0);

         string comPortName = _configuration.GetConfigurationValue("CommFpgaPcNode2x", "ComPortName", "COM1");
         int baudRate = _configuration.GetConfigurationValue("CommFpgaPcNode2x", "BaudRate", 115200);
         Parity parity = _configuration.GetConfigurationValue("CommFpgaPcNode2x", "Parity", Parity.None);
         int dataBits = _configuration.GetConfigurationValue("CommFpgaPcNode2x", "DataBits", 8);
         StopBits stopBits = _configuration.GetConfigurationValue("CommFpgaPcNode2x", "StopBits", StopBits.None);

         _delayBeforeReadMs = _configuration.GetConfigurationValue<uint>("CommFpgaPcNode2x", "DelayBeforeReadMs", 0);
         _pcNodeAddress = _configuration.GetConfigurationValue<uint>("CommFpgaPcNode2x", "PcNodeAddress", 0);

         const int READ_BUF_SIZE = 100;

         try
         {
            _serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits)
            {
               ReadTimeout = 100
            };
         }
         catch (Exception ex)
         {
            _logger.Error(ex);

            if (_serialPort.IsOpen == true)
            {
               _serialPort.Close();
            }
            throw;
         }

         _readBuf = new byte[READ_BUF_SIZE];

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



      /// <summary>
      /// The constructor which opens up a serial port
      /// </summary>
      /// <param name="commFpgaPcNodeAddress">The address of the PC node</param>
      /// <param name="comPortName">The port name. "Com1' for example</param>
      /// <param name="delayBeforeReadMs">The num of ms to wait before a read</param>
      /// <param name="baudRate">The baud rate</param>
      /// <param name="parity">The parity</param>
      /// <param name="dataBits">Number of data bits</param>
      /// <param name="stopBits">Number of Stop Bits</param>
      public CommFpgaPcNode2x(string deviceName, uint pcNodeAddress, string comPortName, uint delayBeforeReadMs, int baudRate = 115200, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
      {
         const int READ_BUF_SIZE = 100;

         try
         {
            _name = deviceName;

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

            _serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits);

            _serialPort.ReadTimeout = 100;

            _delayBeforeReadMs = delayBeforeReadMs;

            _pcNodeAddress = pcNodeAddress;

            _readBuf = new byte[READ_BUF_SIZE];

            _selfTestResult = SelfTestResult.Unknown;
            _state = State.Uninitialized;
         }
         catch (Exception)
         {
            if (_serialPort.IsOpen == true)
            {
               _serialPort.Close();
            }

            throw;
         }
      }

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

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

      /// <summary>
      /// 
      /// </summary>
      public bool DisplayEnabled
      {
         get
         {
            return false;
         }

         set
         {
            throw new NotImplementedException();
         }
      }

      /// <summary>
      /// Dispose of this object
      /// </summary>
      public void Dispose()
      {
         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()
      {
         Initialize(string.Empty);
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="fpga"></param>
      public void Initialize(string fpga)
      {
         lock (_syncObj)
         {
            if (_state == State.Uninitialized)
            {
               if (_serialPort.IsOpen == false)
               {
                  _serialPort.Open();
               }

               ClearBuffer();
               _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()
      {
         _selfTestResult = SelfTestResult.Unknown;
         return _selfTestResult;
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="fpga"></param>
      /// <param name="address"></param>
      /// <returns></returns>
      public uint Read(string fpga, uint address)
      {
         const int NUM_BYTES_EXPECTED_ON_READ = 9;

         int numBytesRead = 0;

         // lock up the FPGA resource
         lock (_syncObj)
         {
            byte[] command = BuildCommand(address, _pcNodeAddress, true);

            for (uint numTries = 0; numTries < 2; numTries++)
            {
               _serialPort.Write(command, 0, command.Length);

               Array.Clear(_readBuf, 0, _readBuf.Length);

               Thread.Sleep((int)_delayBeforeReadMs);

               numBytesRead = _serialPort.Read(_readBuf, 0, _readBuf.Length);

               int numBytesExpectedToRead = NUM_BYTES_EXPECTED_ON_READ;

               if (numBytesRead != numBytesExpectedToRead)
               {
                  //put out diagnostic
                  byte[] errorDiag = new byte[numBytesRead];

                  Array.Copy(_readBuf, errorDiag, numBytesRead);

                  string errMessage = Util.ByteArrayToHexString(errorDiag);

                  if (numTries != 0)
                  {
                     //second time - not a good read
                     throw new Exception("expected to read: " + numBytesExpectedToRead.ToString() + ", read: " + numBytesRead.ToString());
                  }
               }
               else
               {
                  break;//continue processing
               }
            }

            // Grab the last 4 bytes
            uint data = BitConverter.ToUInt32(_readBuf, numBytesRead - 4);

            return data;
         }
      }

      /// <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)
         {
            throw new Exception("Not Implemented");
         }
      }

      /// <summary>
      /// 
      /// </summary>
      public void Reset()
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            ClearBuffer();
         }
      }

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

      /// <summary>
      /// 
      /// </summary>
      public void Shutdown()
      {
         // lock up the FPGA resource
         lock (_syncObj)
         {
            if (_state == State.Ready)
            {
               _serialPort.Dispose();

               _state = State.Uninitialized;
            }
         }
      }

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

      /// <summary>
      /// 
      /// </summary>
      /// <param name="fpga"></param>
      /// <param name="address"></param>
      /// <param name="data"></param>
      public void Write(string fpga, uint address, uint data)
      {
         byte[] command = BuildCommand(address, data, false);

         // lock up the FPGA resource
         lock (_syncObj)
         {
            _serialPort.Write(command, 0, command.Length);
         }
      }

      /// <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)
         {
            throw new Exception("Not Implemented");
         }
      }

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

      #endregion
   }
}
