using System;
using System.Text;
using Microsoft.SPOT.Hardware;
using SWModules;

namespace HWModules
// This is a Singleton instantiation of FIFOQueue class based on
// C# in Depth, Third Edition Jon Skeet
// http://csharpindepth.com/Articles/General/Singleton.aspx
// "a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance"
    
{
    public sealed class EnergyMonitorPump : EnergyMonitorLTC2946
    {
        //TODO P1 this may not need to be a singleton if it is only used in StateBase
        //NOTE: Pump energy monitor can read volts at either ADin or at the sense resistor.  Check schematic and LTC2946 data sheet for details
        private EnergyMonitorPump():base(new I2CDevice.Configuration(0xD4 >> 1, 20),
              EnergyMonitorLTC2946.VoltageSource.SensePlus, 0.025, 5.0, 6)      //0.025 Volts/LSB from datasheet and 0.50 milliAmps/LSB from 0.005 ohm sense resistor on schematic
        {
            underVoltageError = new ErrorHandler(3, underVoltageErrorTS, underVoltageLabel, ErrorHandler.ErrorType.critical, ErrorHandler.setRecoveryMode);
            //underVoltageError.criticalErrorHandler += new ErrorHandler.CriticalErrorHandler(ErrorHandler.setRecoveryMode);
        }

        public static EnergyMonitorPump Instance
        {
            get { return instance ?? (instance = new EnergyMonitorPump()); }
        }

        private static EnergyMonitorPump instance; 

        private static TimeSpan underVoltageErrorTS = new TimeSpan(10000, 0, 0);
        private static StringBuilder underVoltageLabel = new StringBuilder("Pump Under Voltage Error");
        private static ErrorHandler underVoltageError;

        private static EnergyMonitorLTC2946.EM_VandI emData;
        
        private const double busVoltageEndMissionThreshold = 26.5;

        public EnergyMonitorLTC2946.EM_VandI getVoltsAndMilliAmps()
        {
           emData = getVandI();
           if (SV.CurrentState != CPFStates.SMNotRunning)       //TODO P3 might not need to check state as this might only be called after state machine starts
           {
               if (emData.volts < busVoltageEndMissionThreshold)
                   underVoltageError.logError();
           }
           return emData;
        }
    }
}
