/*********************************************************************************************
 * Copyright 2002 - Volian Enterprises, Inc. All rights reserved.
 * Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE
 * ------------------------------------------------------------------------------
 * $Workfile: GroupDefFrm.cs $     $Revision: 17 $
 * $Author: Jsj $   $Date: 7/02/03 9:25a $
 *
 * $History: GroupDefFrm.cs $
 * 
 * *****************  Version 17  *****************
 * User: Jsj          Date: 7/02/03    Time: 9:25a
 * Updated in $/EXE/RefObj/ROEditor
 * made messagebox calls modal by removing the parent window reference
 * 
 * *****************  Version 16  *****************
 * User: Kathy        Date: 5/21/03    Time: 12:50p
 * Updated in $/EXE/RefObj/ROEditor
 * B2003-034: process if only one field. Also, check for all data on okay
 * button select.
 * 
 * *****************  Version 15  *****************
 * User: Kathy        Date: 5/07/03    Time: 1:58p
 * Updated in $/EXE/RefObj/ROEditor
 * B2003-033 fixed
 * 
 * *****************  Version 14  *****************
 * User: Jsj          Date: 4/14/03    Time: 3:01p
 * Updated in $/EXE/RefObj/ROEditor
 * changes resulting from speeding up RO FST file creation
 * 
 * *****************  Version 13  *****************
 * User: Kathy        Date: 3/11/03    Time: 11:25a
 * Updated in $/EXE/RefObj/ROEditor
 * allow extra text on accpageid template
 * 
 * *****************  Version 12  *****************
 * User: Kathy        Date: 12/10/02   Time: 2:26p
 * Updated in $/EXE/RefObj/ROEditor
 * fieldname special char
 * 
 * *****************  Version 11  *****************
 * User: Kathy        Date: 12/02/02   Time: 8:29a
 * Updated in $/EXE/RefObj/ROEditor
 * fieldname replace chars
 * 
 * *****************  Version 10  *****************
 * User: Kathy        Date: 12/02/02   Time: 6:18a
 * Updated in $/EXE/RefObj/ROEditor
 * added status on long ops & check for fieldname change for textbox
 * 
 * *****************  Version 9  *****************
 * User: Kathy        Date: 10/15/02   Time: 2:18p
 * Updated in $/EXE/RefObj/ROEditor
 * mods for new group (toplevel)
 * 
 * *****************  Version 8  *****************
 * User: Kathy        Date: 10/10/02   Time: 10:02a
 * Updated in $/EXE/RefObj/ROEditor
 * accessory page id
 * 
 * *****************  Version 7  *****************
 * User: Kathy        Date: 10/02/02   Time: 1:40p
 * Updated in $/EXE/RefObj/ROEditor
 * clean up
 * 
 * *****************  Version 6  *****************
 * User: Kathy        Date: 9/27/02    Time: 1:14p
 * Updated in $/EXE/RefObj/ROEditor
 * fix digit as first char in fieldname
 * 
 * *****************  Version 5  *****************
 * User: Kathy        Date: 9/25/02    Time: 9:57a
 * Updated in $/EXE/RefObj/ROEditor
 * dev
 * 
 * *****************  Version 4  *****************
 * User: Kathy        Date: 9/19/02    Time: 10:03a
 * Updated in $/EXE/RefObj/ROEditor
 * only allow mods at root 
 * 
 * *****************  Version 3  *****************
 * User: Kathy        Date: 9/11/02    Time: 1:15p
 * Updated in $/EXE/RefObj/ROEditor
 * vlnxml
 * 
 * *****************  Version 2  *****************
 * User: Kathy        Date: 8/28/02    Time: 10:56a
 * Updated in $/EXE/RefObj/ROEditor
 * development
 *********************************************************************************************/


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;
using System.Text;
using RODBInterface;
using ROFields;
using VlnStatus;

namespace ROEditor
{
	/// <summary>
	/// Summary description for GroupDefinition.
	/// </summary>
	public class GroupDefFrm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label lblGroup;
		private System.Windows.Forms.TextBox tbGroup;
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.Label lblPrefix;
		private System.Windows.Forms.Label lblValue;
		private System.Windows.Forms.TextBox tbPrefix;
		private System.Windows.Forms.TextBox tbValue;
		private System.Windows.Forms.Button btnRODef;
		private System.Windows.Forms.Button btnSubDef;
		private System.Windows.Forms.Button btnOK;
		private System.Windows.Forms.Button btnCancel;

		private RODB myrodb;
		private VlnXmlElement elem;
		private string origGroup;
		private string origPrefix;
		private string origValue;
		private int dbtype;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public GroupDefFrm(VlnXmlElement pelem, RODB rodb, string gpname,int idbtype)
		{
			myrodb = rodb;
			elem = pelem;
			origGroup = gpname;
			dbtype=idbtype;			// if new, 3 = user define, must define fields before save.
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			FillInData();
		}

		private string CvtUserFldToFld(string fldname)
		{
			if (fldname.Length < 2)
				return fldname;
			// a digit cannot start an xml fieldname, prepend a "__" to it.
			string tmp0;
			if (char.IsDigit(fldname,0))
				tmp0 = "__" + fldname;
			else
				tmp0 = fldname;
			// an xml fieldname cannot have a space, change it to a "__"
			string tmpstr = tmp0.Replace(" ","__");
			int len = tmpstr.Length;
			int cnt = 0;

			// this is also our sequence that tells us the follow 3 digits is the ascii number (base 10)
			// of the character we replaced.
			string OKpunch = "-._"; 

			string outstr = "";
			int decval;

			while (cnt < len)
			{
				char tmpchr = tmpstr[cnt];
				if(!char.IsLetterOrDigit(tmpchr)&& (OKpunch.IndexOf(tmpchr) == -1) )
				{
					decval = tmpchr;
					outstr += OKpunch + decval.ToString("D3");
				}
				else
				{
					outstr += tmpchr.ToString();
				}
				cnt++;
			}
			return outstr;
		}

		private string CvtFldToUserFld(string fldname)
		{
			string tmpstr0;
			if (fldname.Length < 2) return fldname;
			// an xml element name cannot begin with a digit. we had prepended a "__"
			if (fldname.Substring(0,2) == "__" && char.IsDigit(fldname,2))
				tmpstr0 = fldname.Substring(2,fldname.Length-2);
			else
				tmpstr0 = fldname;
			// an xml element name cannot have a space, we converted to a "__"
			string tmpstr = tmpstr0.Replace("__"," ");
			int len = tmpstr.Length;
			int cur = 0;

			// this is also our sequence that tells us the follow 3 digits is the ascii number (base 10)
			// of the character we replaced.
			string OKpunch = "-._"; 

			string outstr = "";
			int decval, indx;
			if (len <6)
				indx = -1;
			else
				indx=tmpstr.IndexOf(OKpunch,cur);
			string asc_spchar;
			while (indx>=0)
			{
				outstr += tmpstr.Substring(cur,indx-cur);
				asc_spchar = tmpstr.Substring(indx+3,3);
				decval = System.Convert.ToInt16(asc_spchar,10);
				outstr += System.Convert.ToChar(decval).ToString();
				cur = indx+6;
				if (cur+6 > len)
					indx = -1;
				else
					indx = tmpstr.IndexOf(OKpunch,cur);
			}
			if (cur<len) outstr += tmpstr.Substring(cur,len-cur);	

			return outstr;
		}

		private string DetermineGroupName()
		{
			// if group immediately below root, just use text at this node & it can be editted
			// otherwise, parse it according to GroupMenuItem and it's not editable (it 
			// gets editted by editting the data of the group).
			if (elem.ParentNode.Name == "RO_Root")
			{
				this.tbGroup.Enabled = true;
				this.tbPrefix.Enabled = true;
				this.tbValue.Enabled = true;
				return CvtFldToUserFld(origGroup);
			}
			else
			{
				this.tbGroup.Enabled = false;
				this.tbPrefix.Enabled = false;
				this.tbValue.Enabled = false;
				return CvtFldToUserFld(origGroup);
			}
		}
		private void FillInData()
		{
			this.tbGroup.Text = DetermineGroupName();
			// get the accessory prefix & accessory vale. May need to walk up the tree for this.
			// and for a new group, it needs to get it from the parent.
			string accpref, accvalue;
			accpref = elem.GetAttribute("AccPageIDPrefix");
			accvalue = elem.GetAttribute("AccPageID");

			VlnXmlElement parent;
			parent = (VlnXmlElement) elem.ParentNode;
			while (parent != null && (accpref == "" || accvalue==""))
			{
				// walk up tree to get parent.
				if (accpref == "") accpref = parent.GetAttribute("AccPageIDPrefix");
				if (accvalue == "") accvalue = parent.GetAttribute("AccPageID");
				if (parent.Name != "RO_Root")
					parent = (VlnXmlElement) parent.ParentNode;
				else
					parent = null;
			}
			if (accpref != "")
				this.tbPrefix.Text = accpref;
			else
				this.tbPrefix.Text = "";
			
			if (accvalue != "")
				this.tbValue.Text = CvtFldToUserFld(accvalue);
			else
				this.tbValue.Text = "";

			origGroup = this.tbGroup.Text;
			origPrefix = this.tbPrefix.Text;
			origValue = this.tbValue.Text;
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{

			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}


		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.lblGroup = new System.Windows.Forms.Label();
			this.tbGroup = new System.Windows.Forms.TextBox();
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.tbValue = new System.Windows.Forms.TextBox();
			this.tbPrefix = new System.Windows.Forms.TextBox();
			this.lblValue = new System.Windows.Forms.Label();
			this.lblPrefix = new System.Windows.Forms.Label();
			this.btnRODef = new System.Windows.Forms.Button();
			this.btnSubDef = new System.Windows.Forms.Button();
			this.btnOK = new System.Windows.Forms.Button();
			this.btnCancel = new System.Windows.Forms.Button();
			this.groupBox1.SuspendLayout();
			this.SuspendLayout();
			// 
			// lblGroup
			// 
			this.lblGroup.Location = new System.Drawing.Point(24, 8);
			this.lblGroup.Name = "lblGroup";
			this.lblGroup.Size = new System.Drawing.Size(56, 16);
			this.lblGroup.TabIndex = 0;
			this.lblGroup.Text = "Group:";
			// 
			// tbGroup
			// 
			this.tbGroup.Location = new System.Drawing.Point(88, 8);
			this.tbGroup.Name = "tbGroup";
			this.tbGroup.Size = new System.Drawing.Size(248, 22);
			this.tbGroup.TabIndex = 1;
			this.tbGroup.Text = "textBox1";
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.tbValue,
																					this.tbPrefix,
																					this.lblValue,
																					this.lblPrefix});
			this.groupBox1.Location = new System.Drawing.Point(24, 56);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(312, 96);
			this.groupBox1.TabIndex = 2;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Accessory Page Access";
			// 
			// tbValue
			// 
			this.tbValue.Location = new System.Drawing.Point(72, 56);
			this.tbValue.Name = "tbValue";
			this.tbValue.Size = new System.Drawing.Size(216, 22);
			this.tbValue.TabIndex = 3;
			this.tbValue.Text = "textBox1";
			// tbPrefix
			// 
			this.tbPrefix.Location = new System.Drawing.Point(72, 24);
			this.tbPrefix.Name = "tbPrefix";
			this.tbPrefix.Size = new System.Drawing.Size(216, 22);
			this.tbPrefix.TabIndex = 2;
			this.tbPrefix.Text = "textBox1";
			// 
			// lblValue
			// 
			this.lblValue.Location = new System.Drawing.Point(16, 56);
			this.lblValue.Name = "lblValue";
			this.lblValue.Size = new System.Drawing.Size(48, 16);
			this.lblValue.TabIndex = 1;
			this.lblValue.Text = "Value:";
			// 
			// lblPrefix
			// 
			this.lblPrefix.ForeColor = System.Drawing.SystemColors.ControlText;
			this.lblPrefix.Location = new System.Drawing.Point(16, 24);
			this.lblPrefix.Name = "lblPrefix";
			this.lblPrefix.Size = new System.Drawing.Size(48, 16);
			this.lblPrefix.TabIndex = 0;
			this.lblPrefix.Text = "Prefix:";
			// 
			// btnRODef
			// 
			this.btnRODef.Location = new System.Drawing.Point(24, 168);
			this.btnRODef.Name = "btnRODef";
			this.btnRODef.Size = new System.Drawing.Size(312, 24);
			this.btnRODef.TabIndex = 3;
			this.btnRODef.Text = "Referenced Object Definition...";
			this.btnRODef.Click += new System.EventHandler(this.btnRODef_Click);
			// 
			// btnSubDef
			// 
			this.btnSubDef.Location = new System.Drawing.Point(24, 208);
			this.btnSubDef.Name = "btnSubDef";
			this.btnSubDef.Size = new System.Drawing.Size(312, 24);
			this.btnSubDef.TabIndex = 4;
			this.btnSubDef.Text = "Subgroup Definition ...";
			this.btnSubDef.Click += new System.EventHandler(this.btnSubDef_Click);
			// 
			// btnOK
			// 
			this.btnOK.Location = new System.Drawing.Point(24, 248);
			this.btnOK.Name = "btnOK";
			this.btnOK.Size = new System.Drawing.Size(144, 24);
			this.btnOK.TabIndex = 5;
			this.btnOK.Text = "OK";
			this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
			// 
			// btnCancel
			// 
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Location = new System.Drawing.Point(192, 248);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.Size = new System.Drawing.Size(144, 24);
			this.btnCancel.TabIndex = 6;
			this.btnCancel.Text = "Cancel";
			// 
			// GroupDefFrm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
			this.ClientSize = new System.Drawing.Size(368, 293);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.btnCancel,
																		  this.btnOK,
																		  this.btnSubDef,
																		  this.btnRODef,
																		  this.groupBox1,
																		  this.tbGroup,
																		  this.lblGroup});
			this.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.Name = "GroupDefFrm";
			this.Text = "Group Definition";
			this.groupBox1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion
		
		private bool ProcessRROAccPageIDChange(VlnXmlElement mnuele, string newtmpl)
		{
			bool success;
			XmlNode chldnode = (XmlNode) mnuele.FirstChild;
			VlnXmlElement echild;
			while (chldnode != null)
			{
				if (chldnode is VlnXmlElement)
				{
					echild = (VlnXmlElement) chldnode;
					if (echild.Name != "vlnGroup")
					{
						// If this is a group defintion subtree it will only have one
						// child, which is the text definition for the subgroup. Don't
						// include these in the tree.
						int levelCnt = chldnode.ChildNodes.Count;
						string TheMenuTitle = echild.GetAttribute("MenuTitle");
						if ((levelCnt > 1) || (levelCnt==1 && !TheMenuTitle.Equals("")))
						{
							string accid = echild.GetAccPageIDString(newtmpl);
							echild.SetAttribute("AccPageID",accid);
							success = myrodb.RODB_WriteRO(echild);
							if (success==false) return false;
						}
					}
				}
				chldnode = chldnode.NextSibling;
			}
			return true;
		}

		private bool UpdateAccPageID(VlnXmlElement grp, string newtmpl, VlnStatusMessage StatMsgWindow)
		{
			// For this group and below in the xml tree, update Accessory Page ID using the new
			// template.
			bool success;
			string haskids;
			string kidsloaded;
			XmlNode node = (XmlNode) grp.FirstChild;
			VlnXmlElement child;
			while (node != null) 
			{
				if (node is VlnXmlElement)
				{
					child = (VlnXmlElement) node;
					
					// If this is a group menu edit, process group nodes, otherwise
					// process rros.

					if (child.Name == "vlnGroup")
					{
						haskids = child.GetAttribute("HasChild");
						kidsloaded = child.GetAttribute("ChildLoaded");
						if (haskids == "True" && kidsloaded == "False" )
						{
							elem.SetAttribute("TreeNotData","True");
							myrodb.RODB_GetChildData(child,true);
							child.SetAttribute("ChildLoaded","True");
						}
						StatMsgWindow.StatusMessage = child.GetAttribute("MenuTitle"); 
						success = UpdateAccPageID(child, newtmpl, StatMsgWindow);
						if (success == false) return false;

						success = ProcessRROAccPageIDChange(grp, newtmpl);
						if (success==false)return false;
					}
				}
				node = node.NextSibling;
			}
			success = ProcessRROAccPageIDChange(grp, newtmpl);
			if (success==false) return false;
			return true;
		}
		
		private void btnOK_Click(object sender, System.EventArgs e)
		{
			// if the fields were disabled, just return. (Only need to check one of them)
			if(this.tbGroup.Enabled == false) 
			{
				this.Close();
				return;
			}
			// is this is a database level group, and is a user defined type, the
			// accessory page value, fields in use & group fields in use must all be set.
			// (doesn't need a prefix.
			if (elem.ParentNode.Name == "RO_Root" && dbtype==3)   //3 is user defined.
			{
				string strattr;
				strattr = elem.GetAttribute("FieldsInUse");
				if (strattr == null || strattr=="") 
				{
					MessageBox.Show("No fields defined for Referenced Objects","Group Definition Error");
					return;
				}
				strattr = this.tbValue.Text;
				if (strattr == null || strattr=="")
				{
					MessageBox.Show("No Value defined for this group","Group Definition Error");
					return;
				}
				strattr = elem.GetAttribute("GroupFieldsInUse");
				if (strattr == null || strattr=="")
				{
					MessageBox.Show("No fields defined for subgroup","Group Definition Error");
					return;
				}
			}
			bool modaccpageid=false;
			bool modified=false;
			if ((elem.HasAttribute("AccPageID")&&this.tbValue.Text!=origValue) || this.tbValue.Modified)
			{
				string dummy = "";  // need for RODB_GetFIeldsInUse call, won't be used.
				ArrayList AvailList, InUseList;
				//first see if it is a valid 'InUse' Field.
				AvailList = myrodb.RODB_GetFields(elem, (uint) RecordType.Schema);
				InUseList = myrodb.RODB_GetFieldsInUse(elem, AvailList,"FieldsInUse", ref dummy, true);
				int chkbracketo, chkbracketc;   // open & close bracket indexes
				chkbracketo = this.tbValue.Text.IndexOf("<");
				chkbracketc = this.tbValue.Text.IndexOf(">");														
				if (chkbracketo == -1 || chkbracketc == -1) 
				{
					MessageBox.Show("Missing bracket (<or>) in value definition.");
					return;
				}
				//if (chkbracketo != 0 || chkbracketc != this.tbValue.Text.Length-1)
				//{
				//	MessageBox.Show("Value definition contains extraneous text.");
				//	return;
				//}
				// check for more than one field, don't allow this,
				int twobrk = this.tbValue.Text.IndexOf("<",chkbracketo+1);
				if (twobrk != -1)
				{
					MessageBox.Show("Cannot have two fields in accessory page id.");
					return;
				}
				string val = this.tbValue.Text.Substring(chkbracketo+1,chkbracketc-chkbracketo-1);
				// loop thru inuse list and see if it's there.
				bool found = false;
				for(int i=0; i<InUseList.Count; i++)
				{
					ROField rof = (ROField) InUseList[i];
					string inusename = rof.GetFieldname;
					if (inusename == val) 
					{
						found = true;
						break;
					}
				}
				if (found == false)
				{
					MessageBox.Show(this.tbValue.Text+" not in InUse field list");
					return;
				}
				modified = true;
				modaccpageid=true;
				StringBuilder accidattr = new StringBuilder();
				if (chkbracketo>0) 
					accidattr.Append(this.tbValue.Text.Substring(0,chkbracketo+1)); // +1 include the "<"
				else		
					accidattr.Append("<");
				accidattr.Append(CvtUserFldToFld(this.tbValue.Text.Substring(chkbracketo+1,chkbracketc-chkbracketo-1)));
				if (chkbracketc>this.tbValue.Text.Length) 
					accidattr.Append(this.tbValue.Text.Substring(chkbracketc+1,this.tbValue.Text.Length-chkbracketc+1));
				else
					accidattr.Append(">");
				elem.SetAttribute("AccPageID",accidattr.ToString());
//				elem.SetAttribute("AccPageID",CvtUserFldToFld(this.tbValue.Text));
			
			}
			if (this.tbGroup.Text != origGroup)
			{
				XmlNode tmpn = (XmlNode) elem;
				tmpn.FirstChild.Value = tmpn.FirstChild.Value.Replace(origGroup, this.tbGroup.Text);
				modified=true;
			}
			if ((elem.HasAttribute("AccPageIDPrefix")&&this.tbPrefix.Text != origPrefix) || this.tbPrefix.Modified==true)
			{
				elem.SetAttribute("AccPageIDPrefix",this.tbPrefix.Text);
				modified=true;
			}
			bool success=true;
			if (modified==true) success = myrodb.RODB_WriteRO(elem);
			if (modified == true && success == true && modaccpageid==true)
			{
				Cursor.Current = Cursors.WaitCursor;
				VlnStatusMessage StatMsgWindow = new VlnStatusMessage("Status of Accessory Page ID Change");
				success = UpdateAccPageID(elem, this.tbValue.Text,StatMsgWindow);
				Cursor.Current = Cursors.Default;
				StatMsgWindow.Dispose();
			}
			if (success == false)
				MessageBox.Show("Could not save data.");
			this.Close();
		}

		private void btnRODef_Click(object sender, System.EventArgs e)
		{
			RODefFrm rodef = new RODefFrm(elem,myrodb,"FieldsInUse", this.tbGroup.Text, dbtype);
			rodef.ShowDialog();
			// get accpageid, in case field name changed.
			string accvalue = elem.GetAttribute("AccPageID");

			VlnXmlElement parent;
			parent = (VlnXmlElement) elem.ParentNode;
			while (parent != null && accvalue=="")
			{
				// walk up tree to get parent.
				if (accvalue == "") accvalue = parent.GetAttribute("AccPageID");
				if (parent.Name != "RO_Root")
					parent = (VlnXmlElement) parent.ParentNode;
				else
					parent = null;
			}
			if (accvalue != "")
				this.tbValue.Text = CvtFldToUserFld(accvalue);
			else
				this.tbValue.Text = "";
		}
	
		private void btnSubDef_Click(object sender, System.EventArgs e)
		{
			RODefFrm rodef = new RODefFrm(elem,myrodb,"GroupFieldsInUse", this.tbGroup.Text, dbtype);
			rodef.ShowDialog();
		}
	}
}
