using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Hanna.Controls
{
	/// <summary>
	/// Summary description for RoundedRectangle.
	/// </summary>
	public class RoundedRectangle : Shape
	{

		private const int DEFAULT_ROUNDING_RADIUS = 18;
		private int _roundingCornerRadius = DEFAULT_ROUNDING_RADIUS;

		#region construct/dispose/init
		public RoundedRectangle()
		{
			InitializeComponent();
		}

		/// <summary> 
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		/// <summary> 
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		
		#endregion

		#region Component Designer generated code
		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			// 
			// RoundedRectangle
			// 
			this.Name = "RoundedRectangle";
			this.Size = new System.Drawing.Size(64, 64);

		}
		#endregion

		#region overrides
		protected override GraphicsPath GetShapePath(Rectangle rect)
		{
			GraphicsPath path = new GraphicsPath();
			int diameter = this._roundingCornerRadius*2;
			if ( diameter > rect.Height ) diameter = rect.Height;
			if ( diameter > rect.Width  ) diameter = rect.Width;
			Rectangle cornerRect = new Rectangle(rect.X,rect.Y,diameter,diameter);
			if ( ! cornerRect.IsEmpty)
			{
				path.StartFigure();
				path.AddArc(cornerRect,180,90);
				cornerRect.Offset(rect.Width - diameter, 0);
				path.AddArc(cornerRect,270,90);
				cornerRect.Offset(0, rect.Height - diameter);
				path.AddArc(cornerRect,0,90);
				cornerRect.Offset(-(rect.Width-diameter), 0);
				path.AddArc(cornerRect,90,90);
				path.CloseFigure();
			}					
			return path;
		}
		#endregion

		public int RoundingCornerRadius
		{
			get
			{	
				return this._roundingCornerRadius;
			}
			set
			{
				if ( this._roundingCornerRadius != value )
				{
					if ( value >= 0								 && 
						value <= this.ClientRectangle.Height/2  && 
						value <= this.ClientRectangle.Width/2  )					
					{
						this._roundingCornerRadius = value;
						this.SetRegion();
					}
				
					else
					{
						throw new ArgumentException("RoundingRadius must be non-negative and cannot exceed half of control width or height");
					}				
				}
			}
		}
	}
}
