using System.Collections.Generic;
using System;

namespace Me.StefS.Utility{
	public static class EnumerationExtensions {
		public static T First<T>(this IEnumerable<T> enumeration)
		{
			if (enumeration == null) {
				throw new System.ArgumentNullException ("enumeration");
			}
			
			if (!enumeration.Any ()) {
				throw new System.ArgumentOutOfRangeException("enumeration");
			}
			
			T element = default(T);
			IEnumerator<T> enumerator = enumeration.GetEnumerator();
			try{
				while(enumerator.MoveNext()){
					element = enumerator.Current;
					break;
				}
			}
			finally{
				enumerator.Dispose();
			}
			
			return element;
		}
		
		public static bool Any<T>(this IEnumerable<T> enumeration)
		{
			if (enumeration == null) {
				throw new System.ArgumentNullException ("enumeration");
			}
			
			bool any = false;
			IEnumerator<T> enumerator = enumeration.GetEnumerator();
			try{
				while(enumerator.MoveNext()){
					any = true;
					break;
				}
			}
			finally{
				enumerator.Dispose();
			}
			
			return any;
		}

		public static void OutputContentsStringsTo<T>(this IEnumerable<T> enumeration, Action<string> output){
			IEnumerator<T> enumerator = enumeration.GetEnumerator();
			try{
				while(enumerator.MoveNext()){
					output.Invoke(enumerator.Current.ToString());
				}
			}
			finally{
				enumerator.Dispose();
			}
		}
	}
}