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

namespace HWModules
{
    public sealed class EnergyMonitorHotel
        : EnergyMonitorLTC2946
    {
        //TODO P1 this may not need to be a singleton if it is only used in StateBase
        //should be 0XDE
        //NOTE: Hotel energy monitor can only read Volts at sense resistor.  Check schematic and LTC2946 data sheet for details
        private EnergyMonitorHotel()
            : base(new I2CDevice.Configuration(0xDE >> 1, 20), EnergyMonitorLTC2946.VoltageSource.SensePlus, 0.025, 0.50)  //0.025 Volts/LSB from data sheet and 0.50 milliAmps/LSB from 0.05 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 EnergyMonitorHotel Instance
        {
            get { return instance ?? (instance = new EnergyMonitorHotel()); }
        }

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

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

        public EM_VandI getVoltsAndMilliAmps()
        {
            emData = getVandI();
            SV.busVoltage = emData.volts;

            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;
        }
    }
}
