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

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

namespace CommunityServer.Controls
{
	/// <summary>
	/// Summary description for Navigator.
	/// </summary>
	public class NavigationMenu : TemplatedWebControl
	{
		public NavigationMenu()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);

			this.DataBind();
		}

		public override void RenderBeginTag(HtmlTextWriter writer)
		{
			
		}

		public override void RenderEndTag(HtmlTextWriter writer)
		{
			
		}

	

		private string _selected = null;
		public string Selected
		{
			get
			{
				if(_selected == null)
					_selected = Context.Items["SelectedNavigation"] as string;

				return _selected;
			}
			set
			{
				_selected= value;
			}
		}

		private bool _reverse = false;
		public bool Reverse
		{
			get{return _reverse;}
			set {_reverse = value;}
		}


		private Repeater Menu = null;
		private bool useSep = false;
		private bool isFirst = true;
		private string _sep = null;

		public string Seperator
		{
			get
			{
				return _sep;
			}
			set
			{
				_sep= value;
				useSep = true;
			}
		}

		//NOTE: Why is this control being databound so many times?

		public override void DataBind()
		{
			if(Context.Items[this.GetType().ToString()] == null)
			{
				base.DataBind ();

				string cacheKey = "TabUrls-";
				string roleKey = CSContext.Current.RolesCacheKey;
				ArrayList links;

				// If no roleKey, then set it to "Everyone";
				if(roleKey == null)
					roleKey = "Everyone";

				// See if there is anything cached
				links = CSCache.Get(cacheKey+roleKey) as ArrayList;

				// If not, then calculate it and cache it
				if(links == null)
				{
					links = new ArrayList();
					ArrayList tabUrls = Globals.GetSiteUrls().MainNavigationLinks;
					string[] roles = roleKey.ToLower().Split(',');

					// Loop through the links to get the ones they are authorized for
					foreach(CSLink link in tabUrls)
					{
						bool authorized = false;

						// See if they are authorized for this link
						foreach(string role in roles)
						{
							if(link.Roles.ToLower().IndexOf(role.Trim()) != -1)
							{
								authorized = true;
								break;
							}
						}

						// Continue if they're not authorized
						if(authorized == false)
							continue;

						// Otherwise, add it to their links
						links.Add(link);
					}

					// Cache it
					CSCache.Insert(cacheKey+roleKey, links, CSCache.MinuteFactor * 15);
				}

				if(links.Count <= 1)
					useSep = false;

				if(Reverse)
				{
					links = links.Clone() as ArrayList;
					links.Reverse();
				}
				
				Menu.DataSource = links;
				Menu.DataBind();
			}
			Context.Items[this.GetType().ToString()] = true;
		}


		protected override void AttachChildControls()
		{
			Menu = FindControl("Menu") as Repeater;
			Menu.ItemDataBound +=new RepeaterItemEventHandler(Menu_ItemDataBound);
		}

		private void Menu_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if(e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.SelectedItem)
			{
				if(useSep)
				{
					if(!isFirst)
					{
						Literal litSep = e.Item.FindControl("Sep") as Literal;
						litSep.Text = this.Seperator;
					}
					isFirst = false;
				}

				CSLink link = e.Item.DataItem as CSLink;
				HyperLink hl = e.Item.FindControl("MenuItem") as HyperLink;
				hl.NavigateUrl = link.NavigateUrl;
				hl.Text = link.Text;

				if(string.Compare(link.Name,this.Selected,true) == 0)
				{
                    if (hl is ListItemLink)
                    {
                        ((ListItemLink)hl).ListItemCssClass = "currenttab";
                    }
                    else
                    {
                        HtmlGenericControl genericControl = e.Item.FindControl("listItem") as HtmlGenericControl;
                        if (genericControl != null)
                            genericControl.Attributes.Add("class", "currenttab");
                    }
				}

			}
		}
	}
}
