//                           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.Net.Sockets;
using System.Text;
using NLog;
using Raytheon.Common;
using Raytheon.Instruments.Dmm;
using Raytheon.Units;

namespace Raytheon.Instruments
{
   /// <summary>
   /// A keysight implementation of the DMM interface
   /// </summary>
   public class DMMKeysightScpi : IDmm
   {
      #region PrivateMemberVariables

      private const string READ_ERROR_STATUS_CMD = "SYST:ERR?";
      private const string _SELFTESTCMD = "*TST?";
      private const string _RESETCMD = "*RST";
      private const string _MEASUREFRES = "MEAS:FRES? "; //Resistance 4-wire
      private const string _MEASURERES = "MEAS:RES? "; //Resistance 2-wire
      private const string _MEASUREDCVOLT = "MEAS:VOLT:DC? ";
      private const string _MEASUREACVOLT = "MEAS:VOLT:AC? ";

      //Frequency
      private const string _FREQ_SETUP1 = "CONF:FREQ ";
      private const string _FREQ_SETUP2 = "SENS:FREQ:VOLT:RANGE:AUTO OFF";
      private const string _FREQ_SETUP3 = "FREQ:VOLT:RANG ";
      private const string _FREQ_SETUP4 = "SAMPLE:COUNT ";
      private const string _MEASUREFREQ = "READ? ";

      private const string _AUTO = "AUTO";
      private const string _DEFAULT = "DEF";

      private const int _PORT = 5025;
      private const int _READ_TIMEOUT = 5000;
      private byte[] _readBuffer;
      private NetworkStream _tcpStream;
      private string _name;
      private readonly string _address;
      private MeasurementFunction _lastType;
      private double _lastRange;
      private double _lastResolution;
      private State _state;
      private SelfTestResult _selfTestResult;

      private readonly ILogger _logger;

      private readonly IConfigurationManager _configurationManager;
      private readonly IConfiguration _configuration;

      #endregion

      #region PrivateFunctions

      /// <summary>
      /// Dispose of this objects resources
      /// </summary>
      /// <param name="disposing"></param>
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_34461A")]
      protected virtual void Dispose(bool disposing)
      {
         if (disposing)
         {
            if (_state == State.Ready)
            {
               Reset();

               _tcpStream.Dispose();

               _state = State.Uninitialized;
            }
         }
      }

      /// <summary>
      /// Reads frequency from the dmm
      /// </summary>
      /// <param name="range">The range to use on the DMM</param>
      /// <param name="resolution">The resolution to use on the DMM</param>
      /// <param name="voltRange">The voltage range for the measurement</param>
      /// <param name="numReads">The number of reads to make</param>
      /// <returns>The frequency or average of frequencies read</returns>
      private double ReadFrequency(double range, double resolution, double voltRange, double numReads)
      {
         //Setup the frequency measurement
         string command = _FREQ_SETUP1;

         if (range == -1)
         {
            command += _DEFAULT + ", " + _DEFAULT;
         }
         else
         {
            command += range + ", " + resolution;
         }

         command += ";:" + _FREQ_SETUP2 + ";:" + _FREQ_SETUP3 + voltRange;

         //want to read frequency more than once
         if (numReads > 1)
         {
            command += ";:" + _FREQ_SETUP4 + "\n";
         }
         else
         {
            command += "\n";
         }

         // send the command
         IOWrite(command);

         //read the frequency
         command = _MEASUREFREQ + "\n";
         string rspStr = IOQuery(command);

         double frequency = 0.0;

         if (rspStr.IndexOf(',') > -1)
         {
            frequency = GetFrequencyAvg(rspStr);
         }
         else
         {
            frequency = Util.ConvertStringToDouble(rspStr);
         }

         return frequency;
      }

      /// <summary>
      /// Reads resistance
      /// </summary>
      /// <param name="range">The range to use on the DMM</param>
      /// <param name="resolution">The resolution to use on the DMM</param>\
      /// <param name="dmmResistanceType"></param>
      /// <returns>The resistance</returns>
      private double ReadResistance(double range, double resolution, MeasurementFunction resistanceType)
      {
         string command = "";

         if (resistanceType == MeasurementFunction.FourWireResistance)
         {
            command = _MEASUREFRES;
         }
         else if (resistanceType == MeasurementFunction.TwoWireResistance)
         {
            command = _MEASURERES;
         }
         else
         {
            throw new Exception("only 4 or 2 write resistance is acceptable for param type: " + resistanceType.ToString());
         }

         if (range == -1)
         {
            command += _AUTO + ", " + _DEFAULT;
         }
         else
         {
            command += range + ", " + resolution;
         }

         command += "\n";

         string rspStr = IOQuery(command);

         double resistance = Util.ConvertStringToDouble(rspStr);

         return resistance;
      }

      /// <summary>
      /// Reads voltage
      /// </summary>
      /// <param name="range">The range to use on the DMM</param>
      /// <param name="resolution">The resolution to use on the DMM</param>
      /// <returns></returns>
      private double ReadVoltage(double range, double resolution, MeasurementFunction voltageType)
      {
         string command = "";

         if (voltageType == MeasurementFunction.ACVolts)
         {
            command = _MEASUREACVOLT;
         }
         else if (voltageType == MeasurementFunction.DCVolts)
         {
            command = _MEASUREDCVOLT;
         }
         else
         {
            throw new Exception("only ac or dc volt is acceptable for param type: " + voltageType.ToString());
         }

         if (range == -1)
         {
            command += _AUTO + ", " + _DEFAULT;
         }
         else
         {
            command += range + ", " + resolution;
         }

         command += "\n";
         string rspStr = IOQuery(command);

         double dcVoltage = Util.ConvertStringToDouble(rspStr);
         return dcVoltage;
      }

      /// <summary>
      /// Convert scpi data to string
      /// </summary>
      /// <param name="data"></param>
      /// <returns></returns>
      private string ConvertToString(ref byte[] data)
      {
         string rsp = System.Text.Encoding.ASCII.GetString(data);
         return rsp;
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="numbers"></param>
      /// <returns></returns>
      private double GetFrequencyAvg(string numbers)
      {
         string[] numArr = numbers.Split(',');
         double retVal = 0;

         foreach (string val in numArr)
         {
            retVal += Util.ConvertStringToDouble(val);
         }

         retVal = retVal / numArr.Length;

         return retVal;
      }


      /// <summary>
      /// Get the error code.
      /// </summary>
      /// <returns>The error code (number).</returns>
      private int GetErrorCode()
      {
         // not calling IOQuery() here so IOQuery() can call GetErrorCode() after each query

         string command = READ_ERROR_STATUS_CMD + "\n";

         // convert to a byte array
         byte[] commandBuffer = Encoding.ASCII.GetBytes(command);

         // send the data out
         _tcpStream.Write(commandBuffer, 0, commandBuffer.Length);

         // clear our buffer
         Array.Clear(_readBuffer, 0, _readBuffer.Length);

         // read the response
         int numBytesRead = _tcpStream.Read(_readBuffer, 0, _readBuffer.Length);

         // convert to a string
         string rspStr = ConvertToString(ref _readBuffer);

         // parse the response
         string[] tokens = rspStr.Split(',');

         int ret = Util.ConvertStringToInt32(tokens[0]);

         return ret;
      }

      /// <summary>
      /// Send a command to the DMM and get the response
      /// </summary>
      /// <param name="commandString">The command to send</param>
      /// <returns>The DMM response</returns>
      private string IOQuery(string commandString)
      {
         // send the command
         IOWrite(commandString, false);

         // clear our buffer
         Array.Clear(_readBuffer, 0, _readBuffer.Length);

         // read from the response
         int numBytesRead = _tcpStream.Read(_readBuffer, 0, _readBuffer.Length);

         if (numBytesRead == 0)
         {
            throw new Exception($"DMMKeysightScpi:IOQuery() - Number of bytes read from stream was {numBytesRead}");
         }

         // convert response to a string
         string rspStr = ConvertToString(ref _readBuffer);

         // check for errors
         int err = GetErrorCode();
         if (err != 0)
         {
            throw new Exception("DMMKeysightScpi:IOQuery() - returned error code: " + err.ToString());
         }

         return rspStr;
      }

      /// <summary>
      /// Sends a SCPI Command to the instrument.
      /// </summary>
      /// <param name="commandString">The SCPI Command to be sent to the instrument.</param>
      private void IOWrite(string commandString, bool checkForError = true)
      {
         // convert to a byte array
         byte[] commandBuffer = Encoding.ASCII.GetBytes(commandString);

         // send the data out
         _tcpStream.Write(commandBuffer, 0, commandBuffer.Length);

         if (checkForError)
         {
            // check for errors
            int err = GetErrorCode();
            if (err != 0)
            {
               throw new Exception("DMMKeysightScpi:IOWrite() - returned error code: " + err.ToString());
            }
         }
      }

      #endregion

      #region PublicFunctions

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

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

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

         _address = _configuration.GetConfigurationValue(Name, Dmm.ConfigXml.IP_ADDRESS.ToString());

         _lastType = 0;
         _lastRange = 0;
         _lastResolution = 0;

         const int READ_BUFFER_SIZE = 512;
         _readBuffer = new byte[READ_BUFFER_SIZE];

         // created in initialize
         _tcpStream = null;
         _state = State.Uninitialized;
         _selfTestResult = SelfTestResult.Unknown;
      }

      /// <summary>
      /// The constructor which opens the handle to the DMM and performs a self test on the instrument
      /// </summary>
      /// <param name="deviceName">The name of this dmm</param>
      /// <param name="address">The address of the DMM</param>
      public DMMKeysightScpi(string deviceName, string address)
      {
         const int READ_BUFFER_SIZE = 512;

         _name = deviceName;
         _address = address;
         _lastType = 0;
         _lastRange = 0;
         _lastResolution = 0;

         _readBuffer = new byte[READ_BUFFER_SIZE];

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

         // created in initialize
         _tcpStream = null;
         _state = State.Uninitialized;
         _selfTestResult = SelfTestResult.Unknown;
      }

      /// <summary>
      /// The Finalizer which will release resources if required
      /// </summary>
      ~DMMKeysightScpi()
      {
         Dispose(false);
      }

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

      /// <summary>
      /// 
      /// </summary>
      /// <param name="type"></param>
      /// <param name="range"></param>
      /// <param name="resolution"></param>
      public void ConfigureCurrentMeasurement(MeasurementFunction type, Current range, Current resolution)
      {
         throw new NotImplementedException();
         /*_lastType = type;
			  _lastRange = range.Amps;
			  _lastResolution = resolution.Amps;*/
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="type"></param>
      /// <param name="range"></param>
      /// <param name="resolution"></param>
      public void ConfigureVoltageMeasurement(MeasurementFunction type, Voltage range, Voltage resolution)
      {
         if (type != MeasurementFunction.DCVolts && type != MeasurementFunction.ACVolts)
         {
            throw new Exception("only ac or dc volt is acceptable for param type: " + type.ToString());
         }

         _lastType = type;
         _lastRange = range.Volts;
         _lastResolution = resolution.Volts;
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="type"></param>
      /// <param name="range"></param>
      /// <param name="resolution"></param>
      public void ConfigureResistanceMeasurement(MeasurementFunction type, Resistance range, Resistance resolution)
      {
         if (type != MeasurementFunction.FourWireResistance && type != MeasurementFunction.TwoWireResistance)
         {
            throw new Exception("only FourWireResistance or TwoWireResistance is acceptable for param type: " + _lastType.ToString());
         }

         _lastType = type;
         _lastRange = range.Ohms;
         _lastResolution = resolution.Ohms;
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="type"></param>
      /// <param name="range"></param>
      /// <param name="resolution"></param>
      public void ConfigureFrequencyMeasurement(MeasurementFunction type, Frequency range, Frequency resolution)
      {
         if (type != MeasurementFunction.Frequency)
         {
            throw new Exception("only frequency is acceptable for param type: " + _lastType.ToString());
         }

         _lastType = type;
         _lastRange = range.Hertz;
         _lastResolution = resolution.Hertz;
      }

      /// <summary>
      /// Dispose of this objects resources
      /// </summary>
      public void Dispose()
      {
         Dispose(true);

         GC.SuppressFinalize(this);
      }

      /// <summary>
      /// 
      /// </summary>
      public string DetailedStatus
      {
         get
         {
            return "This is a Keysight Dmm";
         }
      }

      /// <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)
         {
            TcpClient dmmSocketConn = new TcpClient(_address, _PORT);
            _tcpStream = dmmSocketConn.GetStream();
            _tcpStream.ReadTimeout = _READ_TIMEOUT;
            _selfTestResult = PerformSelfTest();
            _state = State.Ready;
         }
         else
         {
            throw new Exception("expected the state to be Uninitialized, state was: " + _state.ToString());
         }
      }

      /// <summary>
      /// 
      /// </summary>
      public MeasurementFunction MeasurementType
      {
         get
         {
            throw new NotImplementedException();
         }
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="timeout"></param>
      /// <returns></returns>
      public Current MeasureCurrent(int timeout)
      {
         throw new NotImplementedException();

         /*
			   if (_lastType != MeasurementFunction.DCVolts && _lastType != MeasurementFunction.ACVolts)
			   {
			   throw new Exception("only ac or dc volt is acceptable for param type: " + type.ToString());
			   }

			   return Current.FromAmps(ReadCurrent();*/
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="timeout"></param>
      /// <returns></returns>
      public Frequency MeasureFrequency(int timeout)
      {
         if (_lastType != MeasurementFunction.Frequency)
         {
            throw new Exception("only frequency is acceptable for param type: " + _lastType.ToString());
         }

         return Frequency.FromHertz(ReadFrequency(_lastRange, _lastResolution, _lastRange, 1));
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="timeout"></param>
      /// <returns></returns>
      public Resistance MeasureResistance(int timeout)
      {
         if (_lastType != MeasurementFunction.FourWireResistance && _lastType != MeasurementFunction.TwoWireResistance)
         {
            throw new Exception("only FourWireResistance or TwoWireResistance is acceptable for param type: " + _lastType.ToString());
         }

         return Resistance.FromOhms(ReadResistance(_lastRange, _lastResolution, _lastType));
      }

      /// <summary>
      /// 
      /// </summary>
      /// <param name="timeout"></param>
      /// <returns></returns>
      public Voltage MeasureVoltage(int timeout)
      {
         if (_lastType != MeasurementFunction.DCVolts && _lastType != MeasurementFunction.ACVolts)
         {
            throw new Exception("only ac or dc volt is acceptable for param type: " + _lastType.ToString());
         }

         return Voltage.FromVolts(ReadVoltage(_lastRange, _lastResolution, _lastType));
      }

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

      /// <summary>
      /// 
      /// </summary>
      /// <returns></returns>
      public SelfTestResult PerformSelfTest()
      {
         try
         {
            // change the timeout to account for the long self test
            _tcpStream.ReadTimeout = 30000;

            // send the command and get the response
            string command = _SELFTESTCMD + "\n";
            string rspStr = IOQuery(command);

            // parse the response
            string[] tokens = rspStr.Split('\n');

            int rsp = Util.ConvertStringToInt32(tokens[0].Replace("+", "").Split(',')[0]);


            if (rsp != 0)
            {
               string errorMsg = "returned an error: " + rspStr;
               _selfTestResult = SelfTestResult.Fail;
               throw new Exception(errorMsg);
            }
            _selfTestResult = SelfTestResult.Pass;
         }
         catch (Exception)
         {
            throw;
         }
         finally
         {
            // restore the timeout
            _tcpStream.ReadTimeout = _READ_TIMEOUT;
         }

         return SelfTestResult;
      }

      /// <summary>
      /// 
      /// </summary>
      public void Reset()
      {
         IOWrite(_RESETCMD + "\n");
      }

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

            _tcpStream.Dispose();

            _state = State.Uninitialized;
         }
      }

      #endregion
   }
}
