/*********************************************************************************************
 * Copyright 2002 - Volian Enterprises, Inc. All rights reserved.
 * Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE
 * ------------------------------------------------------------------------------
 * $Workfile: GroupNewFrm.cs $     $Revision: 7 $
 * $Author: Kathy $   $Date: 5/07/03 1:58p $
 *
 * $History: GroupNewFrm.cs $
 * 
 * *****************  Version 7  *****************
 * User: Kathy        Date: 5/07/03    Time: 1:58p
 * Updated in $/EXE/RefObj/ROEditor
 * B2003-033
 * 
 * *****************  Version 6  *****************
 * User: Kathy        Date: 4/04/03    Time: 9:40a
 * Updated in $/EXE/RefObj/ROEditor
 * B2003-030: set HasChild Attribute for new group
 * 
 * *****************  Version 5  *****************
 * User: Kathy        Date: 12/10/02   Time: 2:26p
 * Updated in $/EXE/RefObj/ROEditor
 * fieldname special char
 * 
 * *****************  Version 4  *****************
 * User: Kathy        Date: 12/06/02   Time: 11:58a
 * Updated in $/EXE/RefObj/ROEditor
 * fix new table can't delete without exiting program
 * 
 * *****************  Version 3  *****************
 * User: Kathy        Date: 12/02/02   Time: 8:30a
 * Updated in $/EXE/RefObj/ROEditor
 * fieldname replace chars
 * 
 * *****************  Version 2  *****************
 * User: Kathy        Date: 10/17/02   Time: 11:35a
 * Updated in $/EXE/RefObj/ROEditor
 * don't save twice if continue selected to close
 * 
 * *****************  Version 1  *****************
 * User: Kathy        Date: 10/15/02   Time: 2:24p
 * Created in $/EXE/RefObj/ROEditor
 * new hi level group, form & code
 *********************************************************************************************/

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

namespace ROEditor
{
	/// <summary>
	/// Summary description for GroupNewFrm.
	/// </summary>
	public class GroupNewFrm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button btnCancel;
		private System.Windows.Forms.TextBox tbGroup;
		private System.Windows.Forms.Label lblGroup;
		private System.Windows.Forms.Button btnContinue;
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.RadioButton rbbtnUserDef;
		private System.Windows.Forms.RadioButton rbbtnGraphics;
		private System.Windows.Forms.RadioButton rbbtnSetpoint;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		private RODB myrodb;
		private VlnXmlElement elem;
		private string lastSavedGroup;
		private VlnXmlElement nelem;    // new group element
		private string tbname;			// new group table name
		private string toprecid;		// new group master rec id

		public GroupNewFrm(RODB rodb, VlnXmlElement topelem)
		{
			elem = topelem;
			myrodb = rodb;
			nelem = null;
			toprecid = null;
			tbname = null;
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <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.btnCancel = new System.Windows.Forms.Button();
			this.btnContinue = new System.Windows.Forms.Button();
			this.tbGroup = new System.Windows.Forms.TextBox();
			this.lblGroup = new System.Windows.Forms.Label();
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.rbbtnSetpoint = new System.Windows.Forms.RadioButton();
			this.rbbtnGraphics = new System.Windows.Forms.RadioButton();
			this.rbbtnUserDef = new System.Windows.Forms.RadioButton();
			this.groupBox1.SuspendLayout();
			this.SuspendLayout();
			// 
			// btnCancel
			// 
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Location = new System.Drawing.Point(176, 244);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.Size = new System.Drawing.Size(120, 24);
			this.btnCancel.TabIndex = 10;
			this.btnCancel.Text = "Cancel";
			this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
			// 
			// btnContinue
			// 
			this.btnContinue.Location = new System.Drawing.Point(40, 244);
			this.btnContinue.Name = "btnContinue";
			this.btnContinue.Size = new System.Drawing.Size(106, 24);
			this.btnContinue.TabIndex = 9;
			this.btnContinue.Text = "Continue";
			this.btnContinue.Click += new System.EventHandler(this.btnContinue_Click);
			// 
			// tbGroup
			// 
			this.tbGroup.Location = new System.Drawing.Point(72, 8);
			this.tbGroup.Name = "tbGroup";
			this.tbGroup.Size = new System.Drawing.Size(248, 22);
			this.tbGroup.TabIndex = 8;
			this.tbGroup.Text = "";
			// 
			// lblGroup
			// 
			this.lblGroup.Location = new System.Drawing.Point(8, 8);
			this.lblGroup.Name = "lblGroup";
			this.lblGroup.Size = new System.Drawing.Size(56, 16);
			this.lblGroup.TabIndex = 7;
			this.lblGroup.Text = "Group:";
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.rbbtnSetpoint,
																					this.rbbtnGraphics,
																					this.rbbtnUserDef});
			this.groupBox1.Location = new System.Drawing.Point(24, 56);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(288, 152);
			this.groupBox1.TabIndex = 11;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Group Type";
			// 
			// rbbtnSetpoint
			// 
			this.rbbtnSetpoint.Location = new System.Drawing.Point(48, 64);
			this.rbbtnSetpoint.Name = "rbbtnSetpoint";
			this.rbbtnSetpoint.Size = new System.Drawing.Size(184, 24);
			this.rbbtnSetpoint.TabIndex = 2;
			this.rbbtnSetpoint.Text = "Setpoint Database";
			// 
			// rbbtnGraphics
			// 
			this.rbbtnGraphics.Location = new System.Drawing.Point(48, 96);
			this.rbbtnGraphics.Name = "rbbtnGraphics";
			this.rbbtnGraphics.Size = new System.Drawing.Size(184, 24);
			this.rbbtnGraphics.TabIndex = 1;
			this.rbbtnGraphics.TabStop = true;
			this.rbbtnGraphics.Text = "Graphics Database";
			// 
			// rbbtnUserDef
			// 
			this.rbbtnUserDef.Location = new System.Drawing.Point(48, 32);
			this.rbbtnUserDef.Name = "rbbtnUserDef";
			this.rbbtnUserDef.Size = new System.Drawing.Size(184, 24);
			this.rbbtnUserDef.TabIndex = 0;
			this.rbbtnUserDef.Text = "User Defined Database";
			// 
			// GroupNewFrm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
			this.ClientSize = new System.Drawing.Size(376, 273);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.groupBox1,
																		  this.btnCancel,
																		  this.btnContinue,
																		  this.tbGroup,
																		  this.lblGroup});
			this.Font = new System.Drawing.Font("Tahoma", 9F);
			this.Name = "GroupNewFrm";
			this.Text = "New Group (Database)";
			this.Load += new System.EventHandler(this.GroupNewFrm_Load);
			this.groupBox1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		private void GroupNewFrm_Load(object sender, System.EventArgs e)
		{
		
		}

		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 void btnCancel_Click(object sender, System.EventArgs e)
		{
			if (toprecid != null)
			{
				myrodb.RODB_DeleteGroup((XmlNode)nelem,tbname,toprecid);
			}
			if(nelem!=null)
			{
				XmlNode par = (XmlNode)nelem.ParentNode;
				par.RemoveChild((XmlNode)nelem);
			}
		}

		private void btnContinue_Click(object sender, System.EventArgs e)
		{
			bool success;
			if (this.tbGroup.Text == null || this.tbGroup.Text == "")
			{
				MessageBox.Show("Need to specify group name.");
				return;
			}
			// if this was already saved, i.e. user hit continue button already,
			// just return;
			if (this.tbGroup.Text == lastSavedGroup) 
			{
				this.Close();
				return;
			}
			lastSavedGroup = this.tbGroup.Text;
			int dbtype=-1;
			if (this.rbbtnGraphics.Checked == true) dbtype = 1;
			else if (this.rbbtnSetpoint.Checked == true) dbtype = 2;
			else if (this.rbbtnUserDef.Checked == true) dbtype = 3;
			if (dbtype<0)
			{
				MessageBox.Show("Need to define type of group.");
				return;
			}
			Cursor.Current = Cursors.WaitCursor;
			// make a new table with the next table name id
			tbname = myrodb.RODB_GetNextGroupTable();
			if (tbname == null) 
			{
				Cursor.Current = Cursors.Default;
				return;
			}
			toprecid = myrodb.RODB_AddNewTable(tbname, this.tbGroup.Text);
			if (toprecid == null) 
			{
				Cursor.Current = Cursors.Default;
				return;
			}
			// for the given type, copy over the required fields.
			success = myrodb.RODB_CopyFieldDefs("ROMaster",tbname,dbtype);
			if (success == false) 
			{
				Cursor.Current = Cursors.Default;
				return;
			}
			// create top level group node with input name.
			nelem = (VlnXmlElement) elem.OwnerDocument.CreateElement("vlnGroup");
			nelem.InnerText = CvtUserFldToFld(this.tbGroup.Text);
			nelem.SetAttribute("Table",tbname);
			nelem.SetAttribute("ParentID", "00000000");
			string nrecid = myrodb.RODB_GetNextRecId(tbname);
			nelem.SetAttribute("RecID", nrecid);
			elem.AppendChild((XmlNode) nelem);
			success = myrodb.RODB_InsertGroup(nelem);
			Cursor.Current = Cursors.Default;
			if (success == false) return;
			nelem.SetAttribute("TreeNotData", "True");
			nelem.SetAttribute("MenuTitle", this.tbGroup.Text);
			nelem.SetAttribute("MasterRecID",toprecid);
			nelem.SetAttribute("HasChild", "False");
			
			// if this is a setpoint db or image db, get fields and find those fields needed
			// to define ro & group. This is hardcoded, yuk.
			if(dbtype == 1 || dbtype == 2)
			{
				ArrayList FieldList = myrodb.RODB_GetFields(nelem, (uint) RecordType.Schema);
				string[] fldlist=null, grplist=null;
				ROField rof;
				string curfld;
				StringBuilder Inuse = new StringBuilder();
				// Get list of inuse fields for the rro.
				if (dbtype == 1)
					fldlist = new string[] {"Name", "Image ID", "Image"};
				else
					fldlist = new string[] {"Setpoint ID", "Setpoint Value", "Associated System Component", "Applicability", "Revision", "Short Description",
					  "Description", "Key Assumptions", "Basis", "References"};
				for (int i=0; i< fldlist.Length; i++)
				{
					curfld = fldlist[i];
					for (int j=0; j<FieldList.Count; j++)
					{
						rof = (ROField) FieldList[j];
						if (rof.GetFieldname == curfld)
						{
							if (i==fldlist.Length-1) // last one don't add ' '
								Inuse.Append(rof.GetRecID);
							else
								Inuse.Append(rof.GetRecID+" ");
							break;
						}
					}
				}
				nelem.SetAttribute("FieldsInUse", Inuse.ToString());
				
				// Get list of group inuse fields.
				Inuse.Remove(0,Inuse.Length);
				if (dbtype == 1)
					grplist = new string[] {"Group"};
				else
					grplist = new string[] {"Parameter"};
				for (int i=0; i< grplist.Length; i++)
				{
					curfld = grplist[i];
					for (int j=0; j<FieldList.Count; j++)
					{
						rof = (ROField) FieldList[j];
						if (rof.GetFieldname == curfld)
						{
							if (i == grplist.Length-1) // last, don't add ' '
								Inuse.Append(rof.GetRecID);
							else
								Inuse.Append(rof.GetRecID+" ");
							break;
						}
					}
				}
				nelem.SetAttribute("GroupFieldsInUse", Inuse.ToString());
				if (dbtype == 2)  // Setpoint
				{
					nelem.SetAttribute("RetVal","<Setpoint__Value>");
					nelem.SetAttribute("MenuItem","<Setpoint__Value,5,17> <Short__Description>");
					nelem.SetAttribute("GroupMenuItem","<Parameter>");
					nelem.SetAttribute("AccPageIDPrefix","SP2");
					nelem.SetAttribute("AccPageID","<Setpoint__ID>");
				}
				else if (dbtype == 1)  // image
				{
					nelem.SetAttribute("RetVal","<Image>");
					nelem.SetAttribute("MenuItem","<Name>");
					nelem.SetAttribute("GroupMenuItem","<Group>");
					nelem.SetAttribute("AccPageIDPrefix","IG2");
					nelem.SetAttribute("AccPageID","<Image__ID>");
				}
				success = myrodb.RODB_WriteRO(nelem);
				if (success == false) return;
			}

			// now let the user specify the group name, etc to define the group.
			GroupDefFrm grdef = new GroupDefFrm(nelem,myrodb,nelem.InnerText,dbtype);
			grdef.ShowDialog();
		}
	}
}
