using System;
namespace Chernobyl.Switch
{
///
/// An that fires an event when it's
/// reaches zero. The is reduced by
/// one every time the event
/// handler method is invoked.
///
public class CountdownSwitch : ISwitch
{
///
/// Initializes a new instance of the class.
///
/// The count of this .
/// When this reaches zero, the
/// event will be raised. This
/// is decremented every time
/// is invoked. The value of
/// this parameter must be greater than 0.
/// Thrown if the countdown
/// is 0; you cannot countdown from zero.
public CountdownSwitch(uint count)
{
Count = StartingCount = count;
}
///
/// An event handler that can be assigned to an event. This method will
/// decrement the by one every time it is invoked.
/// When the reaches zero the
/// event will be raised.
///
/// The instance that generated the event.
/// The instance containing the event data.
public void Countdown(object sender, EventArgs e)
{
// if we are already at zero, ignore the countdown.
if(Count != 0)
{
--Count;
if (Count == 0 && SwitchedOn != null)
SwitchedOn(this, EventArgs.Empty);
}
}
///
/// An event that is raised when the has reached
/// zero.
///
public event EventHandler SwitchedOn;
///
/// An event that is raised right after this switch has been reset using
/// the or
/// methods.
///
public event EventHandler SwitchedOff;
///
/// Resets the switch to its original state or the its state after right
/// after its creation. This method will invoke the
/// event.
///
public void Reset()
{
Count = StartingCount;
if(SwitchedOff != null)
SwitchedOff(this, EventArgs.Empty);
}
///
/// An event handler that can be assigned to an event. This event handler
/// will reset the switch to its original state. It is exactly the same
/// as calling .
///
/// The sender of the event.
/// The arguments to the event.
public void Reset(object sender, EventArgs e)
{
Reset();
}
///
/// The current count of this . When this
/// reaches zero, the event
/// will be invoked. This is decremented every time
/// is invoked.
///
public uint Count { get; private set; }
///
/// The starting value of the . This is the value
/// that was received in the constructor.
///
/// Thrown if the starting count
/// is set to 0; you cannot countdown from zero.
public uint StartingCount
{
get { return _startingCount; }
private set
{
if (value == 0)
throw new ArgumentException("The countdown starting count " +
"cannot be zero since you cannot countdown from zero.",
"value");
_startingCount = value;
}
}
///
/// The backing field to .
///
uint _startingCount;
}
}