// *******************************************************************************************
// **                                                                                       **
// **      DCPwrSentry.cs
// **      4/14/2023
// **                                                                                       **
// **      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 2023.
// **                                                                                       **
// **      WARNING: THIS DOCUMENT CONTAINS TECHNICAL DATA AND / OR TECHNOLOGY WHOSE         **
// **      EXPORT OR DISCLOSURE TO NON-U.S.PERSONS, WHEREVER LOCATED, IS RESTRICTED         **
// **      BY THE INTERNATIONAL TRAFFIC IN ARMS REGULATIONS (ITAR) (22 C.F.R.SECTION        **
// **      120-130) OR THE EXPORT ADMINISTRATION REGULATIONS(EAR) (15 C.F.R.SECTION         **
// **      730-774). THIS DOCUMENT CANNOT BE EXPORTED(E.G., PROVIDED TO A SUPPLIER          **
// **      OUTSIDE OF THE UNITED STATES) OR DISCLOSED TO A NON-U.S.PERSON, WHEREVER         **
// **      LOCATED, UNTIL A FINAL JURISDICTION AND CLASSIFICATION DETERMINATION HAS         **
// **      BEEN COMPLETED AND APPROVED BY RAYTHEON, AND ANY REQUIRED U.S.GOVERNMENT         **
// **      APPROVALS HAVE BEEN OBTAINED. VIOLATIONS ARE SUBJECT TO SEVERE CRIMINAL          **
// **      PENALTIES.                                                                       **
// **                                                                                       **
// **      CAPITAL EQUIPMENT/SOFTWARE: THIS TECHNICAL DATA WAS DEVELOPED OR ACQUIRED        **
// **      EXCLUSIVELY AT CONTRACTOR EXPENSE AND IS INTENDED FOR USE ON MULTIPLE            **
// **      PROJECTS/PROGRAMS.                                                               **
// **                                                                                       **
// *******************************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raytheon.Communication;

namespace Raytheon.Instruments
{
    /// <summary>
    /// SHUTS DOWN ALL SUPPLIES WHEN AN OVER CURRENT OR VOLTAGE OCCURS
    /// This interface will define instruments that watch DCPwr supplies
    /// and monitor their over current and voltage limits, when one of the power supplies
    /// trips, the others will be shutdown.
    /// </summary>
    [UmsContract]
    public sealed class DCPwrSentry
    {
        #region Private Fields

        private HashSet<IDCPwr> _Supplies = new HashSet<IDCPwr>();
        private volatile object _SupplyLock = new object();

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="DCPwrSentry"/> class.
        /// </summary>
        public DCPwrSentry()
        {

        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Adds the specified supply to monitor and be shut down if the
        /// other supplies over current or over voltage
        /// </summary>
        /// <param name="supply">The supply.</param>
        [UmsCommand("IDCPwrSentry.Add")]
        public void Add(IDCPwr supply)
        {
            if (null != supply && !_Supplies.Contains(supply))
            {
                lock (_SupplyLock)
                {
                    _Supplies.Add(supply);
                    supply.OverCurrent += new EventHandler<OverCurrentEventArgs>(supply_OverCurrent);
                    supply.OverVoltage += new EventHandler<OverVoltageEventArgs>(supply_OverVoltage);
                }
            }
        }

        /// <summary>
        /// Removes the specified supply to monitor and be shut down if the
        /// other supplies over current or over voltage
        /// </summary>
        /// <param name="supply">The supply.</param>
        [UmsCommand("IDCPwrSentry.Remove")]
        public void Remove(IDCPwr supply)
        {
            if (null != supply && _Supplies.Contains(supply))
            {
                lock (_SupplyLock)
                {
                    _Supplies.Remove(supply);
                    supply.OverVoltage -= this.supply_OverVoltage;
                    supply.OverCurrent -= this.supply_OverCurrent;
                }
            }
        }

        #endregion

        #region Public Events

        /// <summary>
        /// Occurs when any of the supplies over current.
        /// </summary>
        [UmsEvent("IDCPwrSentry.OverCurrent")]
        public event EventHandler<OverCurrentEventArgs> OverCurrent;

        /// <summary>
        /// Occurs when any of the supplies over voltage.
        /// </summary>
        [UmsEvent("IDCPwrSentry.OverVoltage")]
        public event EventHandler<OverVoltageEventArgs> OverVoltage;

        #endregion

        #region Private Event Handlers From Supplies

        private void supply_OverCurrent(object sender, OverCurrentEventArgs e)
        {
            //lock our supply list, no changing mid event handling
            lock (_SupplyLock)
            {
                //turn off all supplies
                ShutdownSupplies();

                //notify listeners
                if (null != OverCurrent)
                {
                    OverCurrent(this, new OverCurrentEventArgs(_Supplies));
                }
            }
        }

        private void supply_OverVoltage(object sender, OverVoltageEventArgs e)
        {
            //lock our supply list, no changing mid event handling
            lock (_SupplyLock)
            {
                //turn off all supplies
                ShutdownSupplies();

                //notify listeners
                if (null != OverVoltage)
                {
                    OverVoltage(this, new OverVoltageEventArgs(_Supplies));
                }
            }
        }

        private void ShutdownSupplies()
        {
            //lock our supply list, no changing mid event handling
            lock (_SupplyLock)
            {
                //turn off all supplies
                foreach (var supply in _Supplies)
                {
                    try
                    {
                        supply.Enabled = false;
                    }
                    catch (InstrumentException)
                    {
                        //catch the instrument exceptions on the supplies we are
                        //trying to shut down that have over current or voltaged
                    }
                }
            }
        }

        #endregion
    }
}
