using System;
using System.Xml;
using nft.framework;
using nft.framework.plugin;
using nft.util;
using nft.ui.mainframe;
using nft.ui.command;
using System.Diagnostics;

namespace nft.contributions.ui
{
	/// <summary>
	/// CtbMenuItem の概要の説明です。
	/// </summary>
	public class CtbMenuItem : Contribution
	{
		
		public readonly string location;

		/// <summary>
		/// Contributes a menu and submenu items to mainmenu.
		/// 
		/// This contribution can add several items at once.
		/// </summary>
        public CtbMenuItem(Plugin p, XmlElement e)
            : base(p, e) 
		{
            XmlElement parent = (XmlElement)XmlUtil.SelectSingleNode(e, "location");
            XmlUtil.SetAttribute(parent, "id", ""); // set dummy id to parse successfuly
            CommandPathHint hint = new CommandPathHint(parent);
			XmlNode entries = XmlUtil.SelectSingleNode(e,"entries");
            if ("ROOT".Equals(hint.Parent))
				hint.Parent = "";
            location = hint.Parent;
			parseNode(entries, hint);
		}

        protected void parseNode(XmlNode node, CommandPathHint hint)
		{
            foreach( XmlNode cn in node.ChildNodes )
			{
				if(cn.Name.Equals("item"))
				{
                    string mid = XmlUtil.GetAttribute(cn, "mid", "").Trim();
                    CommandUI cui = parseItem(cn);
                    hint.ID = mid;
                    CommandManager.TheInstance.RegisterCommand(this, mid, cui, hint, null);
                    if(cn.ChildNodes.Count!=0)
					{
                        CommandPathHint h2 = new CommandPathHint("");
                        h2.Parent = hint.Parent + CommandManager.PathSepalator + mid;				
                        //string p2 = Main.mainFrame.RegisterMenuNode(_id,path,_cap,after,before);
                        parseNode(cn, h2);
					}
				}
			}
		
		}

        protected CommandUI parseItem(XmlNode item)
		{
            string _cap = XmlUtil.GetAttribute(item, "caption", "").Trim();
            TriggerCommandUI cui = new TriggerCommandUI(_cap, item.InnerText, null);
            return cui;
		}
	}
}
