using System;
using System.Windows.Forms;
using Minntech.Common;

namespace Minntech.Common.Settings
{
	/// <summary>
	/// Summary description for SettingsNode.
	/// </summary>
	public class SettingsNode : TreeNode
	{			
		const string LeftTag = "<";
		const string RightTag = ">";
		const string CloseTag = "/";

		string _name	= string.Empty;
		string _value	= string.Empty;
	
		public bool AllowsAdd		= false;
		public bool AllowsEdit		= false;
        public bool AllowsDelete	= false;

		public SettingsNode() : base()
		{
		}
		public SettingsNode ( string SettingName ) : base (string.Empty)
		{
			this.Name = SettingName;
		}
		public SettingsNode ( string SettingName, string SettingValue) : base ( string.Empty )
		{
			this.Name	= SettingName;
			this.Value	= SettingValue;
		}


		public string Name
		{
			get { return this._name; }
			set 
			{ 
				if ( ! ( this._name.Equals (value ) ) )
				{
					this._name = value;
					base.Text = this.DisplayText;
				}
			}
		}
		public string Value
		{
			get { return this._value; }
			set 
			{
				if ( ! ( this._value.Equals ( value ) ) )
				{
					this._value = value;
					base.Text = this.DisplayText;
					//	everything with a value can be edited by default
					this.AllowsEdit = true;
				}
			}
		}
		public string DisplayText
		{
			get 
			{ 
				string rtnVal = this._name;
				if ( this._value != null && this._value != string.Empty )
					rtnVal += Constants.ValueDelimiter + this._value;
				return rtnVal;
			}
		}

		public void AddSetting (SettingsNode Node)
		{
			foreach ( SettingsNode thisNode in this.Nodes )
			{
				if ( Node.Name.ToUpper().Equals(thisNode.Name.ToUpper()) )
					throw new InvalidOperationException ( "Settings Names must be unique!" );
			}
			this.Nodes.Add(Node);
		}

		public override string ToString()
		{
			string rtnVal = this.DisplayText + Constants.NewLine;
			foreach (SettingsNode node in this.Nodes)
				rtnVal += node.ToString(this.DisplayText + Constants.StringDelimiter);
			return rtnVal;
		}
		public  string ToString ( string NodePath )
		{
			string rtnVal = NodePath + this.DisplayText + Constants.NewLine;
			foreach (SettingsNode node in this.Nodes)
				rtnVal += node.ToString(NodePath + this.DisplayText + Constants.StringDelimiter);
			return rtnVal;
		}

		public string ToXML()
		{
			return this.ToXML ( 0 );
		}

		public string ToXML ( int Indentation )
		{

			string	rtnVal = string.Empty;
			for ( int i = 0; i < Indentation; i++ )
				rtnVal += Constants.TabSpaces;

			rtnVal += LeftTag + this.Name + RightTag; 
			if ( this.Nodes.Count> 0)
			{
				rtnVal += Constants.NewLine;
				foreach ( SettingsNode child in this.Nodes )
					rtnVal += child.ToXML ( Indentation + 1 );
				for ( int i = 0; i < Indentation; i++ )
					rtnVal += Constants.TabSpaces;
			}
			return rtnVal + this.Value + LeftTag + CloseTag + this.Name + RightTag + Constants.NewLine;
		}
	}
}
