using System;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// A generic collection for our application's business entities
/// </summary>
public class EntityCollection<T> : IEnumerable<T> where T : AbstractEntity
{
   // data member
   private List<T> _entities;

   /// <summary>
   /// Constructor initializes the internal collection
   /// </summary>
	public EntityCollection()
	{
      _entities = new List<T>();
	}

   /// <summary>
   /// Add a entity to the collection
   /// </summary>
   public void Add(T entity)
   {
      _entities.Add(entity);
   }

   /// <summary>
   /// Indexer that allows a collection element to be retrieved by a numeric index
   /// </summary>
   public T this[int index]
   {
      get {
         if (index >= 0 && index < _entities.Count)
            return _entities[index];
         else
            return default(T);
      }
   }

   /// <summary>
   /// Search for the customer with the passed id value
   /// </summary>
   public T FindById(int id)
   {
      foreach (T entity in _entities)
      {
         if (entity.Id == id)
            return entity;
      }
      return null;
   }

   /// <summary>
   /// Checks whether the collection is valid. It does this by asking
   /// each element in the collection to verify if it is valid
   /// </summary>
   public bool IsValid()
   {
      bool valid = true;
      foreach (T entity in _entities)
      {
         if (!entity.IsValid)
            valid = false;
      }
      return valid;
   }

   /// <summary>
   /// Must implement GetEnumerator for IEnumerable&lt;T&gt;
   /// 
   /// Implementing this interface allows collection to be iterated using a foreach
   /// (and thus allows collection to be used for data binding)
   /// </summary>
   public IEnumerator<T> GetEnumerator()
   {
      return _entities.GetEnumerator();
   }

   /// <summary>
   /// Must also implement GetEnumerator for IEnumerable to allow for iteration.
   /// </summary>
   IEnumerator IEnumerable.GetEnumerator()
   {
      return GetEnumerator();
   }

}
