using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace pcd_g1
{
	public class WidghetsManager
	{
		int modalCount = 0;
		public bool HasModal
		{
			get
			{
				return modalCount > 0;
			}
		}

		public delegate void WidghetsEndedEventHandler(IWidghet widghet);
		public event WidghetsEndedEventHandler OnWidghetsEnded;

		private void widghetsEndedEvent(IWidghet widghet)
		{
			if (OnWidghetsEnded != null)
				OnWidghetsEnded(widghet);
		}

		List<IWidghet> widghets = new List<IWidghet>();

		public void Update(int keyStatus, bool onlyModal)
		{
			IWidghet p;
			int i = 0;
			IWidghet[] tmpWidghtLst = widghets.ToArray(); //widghetsEndedEvent中でwidghetsが変更される可能性がある
			for(i = 0; i < tmpWidghtLst.Length; i++)
			{
				p = tmpWidghtLst[i];
				if(widghets.Contains(p))
				{
					if (!p.IsSleeping && (!onlyModal || p.IsModal))
					{
						if (p.Update(keyStatus))
						{
							widghetsEndedEvent(p);
							Remove(p);
						}
					}
				}
			}
		}

		public void Draw(Graphics g)
		{
			foreach (var p in widghets)
			{
				if (p.Visibility)
				{
					g.ResetTransform();
					g.TranslateTransform(p.X, p.Y);
					p.Draw(g, p.Width, p.Height);
				}
			}
		}

		public void Add(IWidghet item)
		{
			if (!widghets.Contains(item))
			{
				widghets.Add(item);
				if (item.IsModal) modalCount++;
			}
		}

		public void AddRange(IWidghet[] items)
		{
			widghets.ForEach(p => Add(p));
		}

		public void Clear()
		{
			widghets.Clear();
			modalCount = 0;
		}

		public bool Contains(IWidghet item)
		{
			return widghets.Contains(item);
		}

		public int Count
		{
			get
			{
				return widghets.Count();
			}
		}

		public bool Remove(IWidghet item)
		{
			if (widghets.Contains(item) && item.IsModal) modalCount--;
			return widghets.Remove(item);
		}

		public bool RemoveAt(int index)
		{
			if (index < Count)
			{
				if(widghets[index].IsModal) modalCount--;
				widghets.RemoveAt(index);
				return true;
			}
			else
			{
				return false;
			}
		}
		
	}
}
