//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.ComponentModel;
using System.Web.UI.WebControls;
using CommunityServer.Components;

namespace CommunityServer.Galleries.Controls
{
	/// <summary>
	/// Summary description for ParentCategoryDropDown.
	/// </summary>
	public class ParentCategoryDropDown : DropDownList
	{

		#region Public Properties

		[DefaultValue( -1 )]
		public virtual int SectionID
		{
			get
			{
				Object state = ViewState["SectionID"];
				if(state != null)
					return (int)state;
				return -1;
			}
			set { ViewState["SectionID"] = value; }
		}

		[DefaultValue(false)]
		public virtual bool EnableAllSelection
		{
			get
			{
				Object state = ViewState["EnableAllSelection"];
				if(state != null)
					return (bool)state;
				return false;
			}
			set { ViewState["EnableAllSelection"] = value; }
		}

		[DefaultValue(true)]
		public virtual bool EnableRootSelection
		{
			get
			{
				Object state = ViewState["EnableRootSelection"];
				if(state != null)
					return (bool)state;
				return true;
			}
			set { ViewState["EnableRootSelection"] = value; }
		}

		public int SelectedCategoryID
		{
			get
			{
				if(base.SelectedValue != "")
					return int.Parse(SelectedValue);
				else
					return 0;
			}
			set
			{
				if(base.SelectedValue != "")
					Items.FindByValue( base.SelectedValue ).Selected = false;
				if(value > 0)
					Items.FindByValue( value.ToString() ).Selected = true;
			}
		}
		#endregion

		public override void DataBind()
		{
			base.DataBind();
			Items.Clear();

			if(EnableAllSelection)
				Items.Add( new ListItem( "All", "-1" ) );

			if(EnableRootSelection)
				Items.Add( new ListItem( "Root", "0" ) );

			if(SectionID != -1)
				RecursiveAddCategories(0, "--", PostCategories.GetCategories(SectionID, true, 0));
		}

		private void RecursiveAddCategories(int depth, string prefix, ArrayList categories)
		{
			foreach(PostCategory category in categories)
			{
				Items.Add( new ListItem( prefix + " " + category.Name, category.CategoryID.ToString() ));
				
				ArrayList subCategories = PostCategories.GetCategories(category.SectionID, true, category.CategoryID);
				if(subCategories.Count > 0)
					RecursiveAddCategories(depth + 1, prefix + "--", subCategories);
			}
		}

	}
}
