// $Author: asskoala $
// $Date: 2005/12/11 21:07:21 $
// $Revision: 1.1 $

using System;
using System.Drawing;

namespace Icarus.LUCIE
{
	/// <summary>
	/// Specifies how the components in the grid will be laid out.
	/// </summary>
	public enum Layout 
	{
		Row,
		Column
	}

	/// <summary>
	/// This is a grid of components.
	/// </summary>
	/// Basically, we can add a bunch of components to this control and they will be nicely laid out in a row or column.
	public class ComponentGrid : AbstractComponent
	{
		/// <summary>
		/// The layout of the grid.
		/// </summary>
		private Layout mLayout;

		/// <summary>
		/// Initializes the component grid.
		/// </summary>
		/// <param name="l">How will the components be laid out?</param>
		public ComponentGrid(Layout l)
		{
			this.Layout = l;

			//Register to listen for child changes:
			this.ChildrenChanged += new ChildCallback(ComponentGrid_ChildrenChanged);
		}

		/// <summary>
		/// Gets or sets how the components are laid out.
		/// </summary>
		public Layout Layout
		{
			get { return mLayout; }
			set
			{
				this.mLayout = value;
				this.LayOutComponents();
			}
		}

		/// <summary>
		/// This function lays out the components and updates my own dimensions.
		/// </summary>
		private void LayOutComponents()
		{
			//The position for the next component:
			Point position = new Point(0, 0);

			//The maximum dimension in the direction perpendicular to the one being laid out in:
			int maximumDimension = 0;

			foreach (AbstractComponent child in this.Children)
			{
				child.Location = position;

				switch (this.Layout)
				{
					case Layout.Column:
						maximumDimension = Math.Max(maximumDimension, child.Size.Width);
						position.Y += child.Size.Height;
						break;

					case Layout.Row:
						maximumDimension = Math.Max(maximumDimension, child.Size.Height);
						position.X += child.Size.Width;
						break;
				}
			}

			switch (this.Layout)
			{
				case Layout.Column:
					this.Size = new Size(maximumDimension, position.Y);
					break;

				case Layout.Row:
					this.Size = new Size(position.X, maximumDimension);
					break;
			}
		}

		protected override void RenderSelf(System.Drawing.Rectangle coordinates, Icarus.Graphics.Animation.IRenderParameters parameters)
		{
			//Nothing special to do. The rendering of children is done on a higher level.
		}

		private void ComponentGrid_ChildrenChanged(AbstractComponent sender, AbstractComponent child)
		{
			//Update layout:
			this.LayOutComponents();
		}
	}
}
