using System;
using System.Collections.Generic;
using Chernobyl.Collections.Generic.Event;
using Chernobyl.Event;
namespace Chernobyl.Creation.Collections
{
///
/// An that stores items created by an .
///
public class Warehouse : DecoratingEventEnumerable
{
///
/// Initializes a new instance of the class.
///
/// Instance to listen to for item creation. Use
/// for multiple instances.
public Warehouse(IBuilder builder)
: this(builder, new List())
{}
///
/// Initializes a new instance of the class.
///
/// Instance to listen to for item creation. Use
/// for multiple instances.
/// The that is to be used to store items.
/// Thrown if is null.
public Warehouse(IBuilder builder, ICollection items)
: base(items)
{
items.ThrowIfNull(nameof(items));
builder.ThrowIfNull(nameof(builder));
Items = items;
builder.Created += OnItemCreated;
}
///
/// An event handler that can be assigned to any event which notifies
/// client code of an items creation. When invoked this method will
/// store the created item, if applicable, in this instance's internal
/// collection so that it can be iterated over.
///
/// The sender of the event.
/// The argument that contains the event data.
public void OnItemCreated(object sender, CreationEventArgs e)
{
if (e.Cancelled == false && e.Error == null)
{
Items.Add(e.CreatedInstance);
ItemsAddedHandler?.Invoke(this, new ItemsEventArgs(e.CreatedInstance));
}
}
///
/// The of items that have been built.
///
protected ICollection Items { get; }
}
///
/// Utility and extension methods for .
///
public static class WarehouseExt
{
///
/// Creates a to store items produced by .
///
public static IEventEnumerable Warehouse(this IBuilder builder) => new Warehouse(builder);
}
}