using System.Collections.Generic;
using Raytheon.Instruments.PowerSupply;

namespace ProgramLib
{
   /// <summary>
   /// Stores voltage and current reading for each power module
   /// </summary>
   internal class PowerSupplySharedData
   {
      private object syncObj = new object();
      private Dictionary<string,object> syncObjDict = new Dictionary<string, object>();
      private Dictionary<string, PowerSupplyData> _powerSupplyDataDict = new Dictionary<string, PowerSupplyData>();

      /// <summary>
      /// Set data for a power supply module
      /// </summary>
      public void SetData(string moduleName, double voltage, double current, PowerSupplyModuleInfo powerSupplyModuleInfo)
      {
         lock (syncObj)
         {
            if (!syncObjDict.ContainsKey(moduleName))
            {
               // create a mutex for each module
               syncObjDict[moduleName] = new object();

               _powerSupplyDataDict[moduleName] = new PowerSupplyData();
            }
         }

         lock (syncObjDict[moduleName])
         {
            _powerSupplyDataDict[moduleName].Voltage = voltage;
            _powerSupplyDataDict[moduleName].Current = current;
            _powerSupplyDataDict[moduleName].Initialized = true;
            _powerSupplyDataDict[moduleName].PowerSupplyModuleInfo = powerSupplyModuleInfo;
         }
      }

      /// <summary>
      /// Get data for a power supply module
      /// </summary>
      public PowerSupplyData GetData(string moduleName)
      {
         lock (syncObj)
         {
            if (!syncObjDict.ContainsKey(moduleName))
            {
               // create a mutex for each module
               syncObjDict[moduleName] = new object();

               _powerSupplyDataDict[moduleName] = new PowerSupplyData();
            }
         }

         lock (syncObjDict[moduleName])
         {
            PowerSupplyData data = null;
            if (_powerSupplyDataDict.ContainsKey(moduleName))
            {
               data = _powerSupplyDataDict[moduleName];
            }

            return data;
         }
      }

      /// <summary>
      /// Set each power supply data to uninialized
      /// </summary>
      public void ResetAll()
      {
         foreach (KeyValuePair<string, PowerSupplyData> entry in _powerSupplyDataDict)
         {
            lock (syncObj)
            {
               if (!syncObjDict.ContainsKey(entry.Key))
               {
                  // create a mutex for each module
                  syncObjDict[entry.Key] = new object();
               }
            }

            lock (syncObjDict[entry.Key])
            {
               entry.Value.Reset();
            }
         }
      }
   }
}
