using System;
using System.Collections.Generic;
using System.Web.UI;

namespace DebriefingSoftware.Common
{
	public static class ControlExtensions
	{
		private static readonly object syncRoot = new object();

		public static T FindOrNull<T>(this Control control, string id) where T : class
		{
			return (control.FindControl(id) as T);
		}

		public static T FindOrCreate<T>(this Control control, string id) where T : class
		{
			var findControl = control.FindControl(id);

			if (findControl == null)
				return default(T);

			return (findControl as T);
		}

		public static T FindRecursive<T>(this Control control, string id) where T : class
		{
			foreach (Control control2 in control.Controls)
			{
				if (((control2.ID != null) &&
					 string.Equals(control2.ID, id, StringComparison.InvariantCultureIgnoreCase)) && (control2 is T))
				{
					return (control2 as T);
				}
				T local = control2.FindRecursive<T>(id);
				if (local != null)
				{
					return local;
				}
			}
			return null;
		}

		public static T FindRecursiveOrCreate<T>(this Control control, string id) where T : class
		{
			foreach (Control control2 in control.Controls)
			{
				if (((control2.ID != null) &&
					 string.Equals(control2.ID, id, StringComparison.InvariantCultureIgnoreCase)) && (control2 is T))
				{
					return (control2 as T);
				}
				T local = control2.FindRecursiveOrCreate<T>(id);
				if (local != null)
				{
					return local;
				}
			}
			return default(T);
		}

		public static List<T> GetControlListOnCreateNew<T>(this Control root, Type type) where T : Control
		{
			lock (syncRoot)
			{
				var controlList = new List<T>();
				FindRecursiveAll<T>(root, type, controlList);
				return controlList;
			}
		}



		public static void FindRecursiveAll<T>(Control root, Type type, List<T> list) where T : Control
		{
			if (root.GetType() == type)
			{
				list.Add((T)root);
			}
			else
			{
				foreach (Control ctl in root.Controls)
				{
					FindRecursiveAll(ctl, type, list);
				}
			}
		}
	}
}
