using System;
using System.Data; 
using System.Web.UI.WebControls;   
using System.ComponentModel;

using Meta.Web;
using Meta.Web.Security; 
using Meta.Web.Controls; 
using Meta.Web.Controls.Template; 
using MetaSite.Components.Providers;

namespace MetaSite.Components.Controls.Views
{
	/// <summary>
	/// AdminHeader ¡£
	/// </summary>
	public class AdminHeader : BaseTemplateControl
	{		
		Menubar menus;
		Menubar submenus;
		Literal literal;
		ContextData context; 
		string selectmenu;
		
		protected override void AttachChildControls()
		{	
			context = ContextData.Current; 

			menus = (Menubar) FindControl("menus");		
			submenus = (Menubar) FindControl("submenus");
			literal = (Literal) FindControl("literal");

			literal.Text = "<b><font size=\"5\">ºóÌ¨¹ÜÀí</font></b>";

			AdminSettings.FileLocation =  "~/admin.config";
			
			ToolItemCollection tools = AdminSettings.GetTools();

            menus.MenuItemStyle.CssClass = "adminmenu";
            submenus.MenuItemStyle.Width = 80; 
			menus.Items.Clear();
			submenus.Items.Clear();  

			selectmenu = GetSelect(tools.ToolItems);//System.IO.Path.GetFileNameWithoutExtension(Page.Request.FilePath);		

			AddItem(menus,tools.ToolItems);  
		}

		private string GetSelect(ToolItem[] tools)
		{
			string select = System.IO.Path.GetFileNameWithoutExtension(Page.Request.FilePath).ToLower();	

			foreach( ToolItem tool in tools )
			{
				if ( tool.Name.ToLower() == select)
				{
					return select;
				}

				if ( tool.HasSelects )
				{
                    string[] ss = tool.Selects.Split(',');
  
					foreach(string s in ss)
					{
						if ( s.ToLower() == select)
							return tool.Name.ToLower(); 
					}
				}				
			}		

			return "default";
		}

		private void AddItem( Menubar bar,ToolItem[] tools )
		{
			foreach( ToolItem tool in tools )
			{
				bool show = true;

				if ( tool.HasRoles )
				{
					show = false;
					string[] rs = tool.Roles.Split(','); 
					foreach(string r in rs)
					{
						if( Roles.IsUserInRole(r))
						{
							show = true;
							break;
						}
					}					
				}

				if ( !show)
					continue;

				MenubarItem mb = new MenubarItem();
				mb.Text = tool.Text;
				mb.ID = tool.Name;	

				if (tool.Name.ToLower() == selectmenu )
				{
                    mb.Selected = true;
					if (tool.HasChildren )
						AddItem(submenus,tool.Children);					
				}
			
				mb.NavigateUrl = tool.Href;	
				mb.Target = tool.Target;
			
				bar.Items.Add(mb);
			}

			if( bar.ID == "submenus")
			{
				MenubarItem m = new MenubarItem();				
				bar.Items.Add(m);
			}
				
		}
	}
}
