using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Chernobyl.Utility;
namespace Chernobyl.Collections.Generic.Event
{
///
/// Adds or removes items from an when dictated
/// by events.
///
/// The type of item being added/removed to/from the
/// .
public class AddRemove
{
///
/// Initializes a new instance of the class.
///
/// The instances that are to be added or removed from
/// .
/// True if should
/// be added to immediately.
public AddRemove(IEnumerable items, bool addImmediately)
: this(items, null, addImmediately)
{}
///
/// Initializes a new instance of the class.
///
/// The instances that are to be added or removed from
/// .
/// The that is to
/// to have the added to it or removed from it.
/// True if should
/// be added to cref="collection"/> immediately.
public AddRemove(IEnumerable items, ICollection collection, bool addImmediately)
{
Items = items;
Collection = collection;
if(addImmediately)
Add(this, EventArgs.Empty);
}
///
/// An event handler that, when invoked, adds the to
/// .
///
/// The sender of the event.
/// The instance containing the
/// event data.
public void Add(object sender, EventArgs e)
{
if(Collection != null)
Collection.AddRange(Items);
_addLastInvoked = true;
}
///
/// An event handler that, when invoked, removes the
/// from .
///
/// The sender of the event.
/// The instance containing the
/// event data.
public void Remove(object sender, EventArgs e)
{
if (Collection != null)
Collection.RemoveRange(Items);
_addLastInvoked = false;
}
///
/// The instances that are to be added or removed from
/// .
///
public IEnumerable Items
{
get { return _items; }
private set
{
value.ThrowIfNull("value");
_items = value;
}
}
///
/// The that is to to have the
/// added to it or removed from it. Setting this
/// property will cause the to be removed from the
/// old value of this property and added to the new value but only if the
/// were added to the previous value by this type.
/// This value can be set to null, in which case, addition/removal is
/// disabled.
///
public ICollection Collection
{
get { return _collection; }
set
{
ICollection previousItems = _collection;
_collection = value;
if (_addLastInvoked)
{
if (previousItems != null)
previousItems.RemoveRange(Items);
if (_collection != null)
_collection.AddRange(Items);
}
}
}
///
/// True if was the last method
/// invoked, false if otherwise.
///
bool _addLastInvoked;
///
/// The backing field to .
///
IEnumerable _items;
///
/// The backing field to .
///
ICollection _collection;
}
}