/*********************************************************************************************
 * Copyright 2021 - Volian Enterprises, Inc. All rights reserved.
 * Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE
 * ------------------------------------------------------------------------------
 * $Workfile: CmpRpt.cs $     $Revision: 3 $
 * $Author: Jsj $   $Date: 6/08/05 4:31p $
 *
 * $History: CmpRpt.cs $
 * 
 * *****************  Version 3  *****************
 * User: Jsj          Date: 6/08/05    Time: 4:31p
 * Updated in $/EXE/RefObj/CmpRpt
 * cleanup
 * 
 * *****************  Version 2  *****************
 * User: Jsj          Date: 1/08/04    Time: 2:51p
 * Updated in $/EXE/RefObj/CmpRpt
 * constructor of  RODB() class changed
 * 
 * *****************  Version 1  *****************
 * User: Kathy        Date: 11/11/02   Time: 7:17a
 * Created in $/EXE/RefObj/CmpRpt
 *********************************************************************************************/
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Data;
using RODBInterface;
using VlnStatus;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
// CmpRpt reads data for the RO database and puts the data into the
// temporary file, 'print.tmp'. After this, it is sorted and printed.
namespace CmpRpt
{
	// Form1 just acts as the container for this app.
	public class Form1 : System.Windows.Forms.Form
	{
		/// 
		/// Required designer variable.
		/// 
		private System.ComponentModel.Container components = null;
		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			// B2019-082 set the date format on the VEPROMS.exe thread to U.S. for i/o of a date string
			//           this is to correct an issue for a UAE customer who could not open some procedures due to the desktop date setting using the "DD/MM/YYYY" instead of the "MM/DD/YYYY" format
			//           NOTE: not doing the "Using System.Threading;" statement at beginning of file because it conflicts with the declaration of the "Timer" variable
			System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
		}
		/// 
		/// Clean up any resources being used.
		/// 
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		#region Windows Form Designer generated code
		/// 
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// 
		private void InitializeComponent()
		{
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(292, 273);
			this.Name = "Form1";
			this.Text = "Form1";
		}
		#endregion
		/// 
		/// The main entry point for the application.
		/// 
		[STAThread]
		static void Main(string[] args)
		{
			if (args.Length <= 0) return; // nothing to do
			bool success;
			VlnXmlElement rootXml;
			VlnXmlDocument myroXmlDoc;
			string recid = null;
			string tbl = null;
			RODB myrodb = null;
			// the next two lists contain group headers for the reports.
			ArrayList headers = new ArrayList();
			ArrayList reversehdrs = new ArrayList();
			//if (args.Length <= 0) return;
			//// if an RO directory path was passed in, then change the
			//// current working directory to it.
			//// this path will also be used to generate a connection string
			//// for the Access database.
			//if (args.Length == 2)
			//{
			//    //				MessageBox.Show(args[1],"args[1]");
			//    string path = args[0];
			//    Directory.SetCurrentDirectory(path);
			//    tbl = args[1].Substring(0, 4);
			//    //tbl = args[1].Substring(13,4);
			//    //    recid = args[1].Substring(17,8);
			//    if (args[1].Length > 4)
			//        recid = args[1].Substring(4, 8);
			//    //				myrodb = new RODB(path);
			//}
			//else
			//{
			//    tbl = args[0].Substring(0, 4);
			//    recid = args[0].Substring(4, 8);
			//    //				myrodb = new RODB(Directory.GetCurrentDirectory());
			//}
			/******/
			// if an RO directory path was passed in, then change the
			// current working directory to it.
			// this path will also be used to generate a connection string
			// for the Access database.
			string roIdArg = BuildROList(args);
			string[] roIDList = roIdArg.Split(',');
			// If the args array contains more than 3 elements remove the extra ones.  The fourth argument (PC=...) is handled in the BuildROList
			// method above.  If the args array contains more than 3 elements the working dir will not be correctly be set and the report will fail.
			// The calling code file (DisplayReports.cs) at this time will only send up to 4 args.
			//List args2 = new List(args);
			//for (int i = 0; i < args2.Count; i++)
			//	{
			//		if (i > 2) {
			//			args2.RemoveAt(i);
			//		}					
			//	}
			////args2.RemoveAt(3);
			//args = args2.ToArray();
			//if (args.Length == 2 || args.Length == 3)
			//{
				string path = args[0];
				Directory.SetCurrentDirectory(path);
			//}
			if (SqlConnectionStr != null)
				myrodb = new SqlRODB(Directory.GetCurrentDirectory(), SqlConnectionStr, false);
			else
			{
				myrodb = new AccessRODB(Directory.GetCurrentDirectory());
				// if using access, be sure that the data has not been converted. When converted a record will be inserted w/ type = 8 and the info
				//    will contain the connection string.
				string constring = myrodb.RODB_HasBeenConverted();
				if (constring != null)
				{
					MessageBox.Show("This Referenced Object Database has been converted to sql. Attempting to use the sql version of the database.  If this does not work, contact your Database Administrator", "RO access problem");
					SqlConnectionStr = constring;
					myrodb.dbProviderType = (int)RODB.DB_PROVIDER.SQL_SERVER;
					myrodb = new SqlRODB(Directory.GetCurrentDirectory(), SqlConnectionStr, true);
				}
			}
			VlnXmlElement rptele = null;
			// Add the root to the tree
			myroXmlDoc = myrodb.RODB_GetRoot();
			rootXml = (VlnXmlElement)myroXmlDoc.FirstChild;
			success = myrodb.RODB_GetRootGroups(rootXml);
			if (success == false) return;
			VlnStatusMessage showStat = null;
			VlnStatusBar showStatBar = null;
			int inc = 0;
			int bmax = roIDList.Length;
			if (roIDList.Length > 50)
			{
				showStatBar = new VlnStatusBar("Retrieving RO Information");
				showStatBar.BarMax = bmax;
				showStatBar.StatMsg = "Retrieving RO Information";
			}
			else
			{
				showStat = new VlnStatusMessage("Retrieving RO Information");
				showStat.StatusMessage = "Reading RO Information";
			}
			Application.DoEvents();
			foreach (string roid in roIDList)
			{
				if (showStatBar != null)
				{
					showStatBar.StatMsg = string.Format("Retrieving RO {0} of {1}", inc++, bmax);
					showStatBar.BarValue = inc;
				}
				tbl = roid.Substring(0, 4);
				recid = (roid.Length > 4) ? roid.Substring(4, 8) : null;
				// if the table & recid = all zeros, we have a request
				// for all ROs, otherwise it's a request for specific RO(s)
				if (tbl == "0000" && recid != null && recid == "00000000")
				{
					// the report element becomes the root.
					rptele = rootXml;
				}
				else
				{
					// from the input tbl string, get a table name.
					int itbl = System.Convert.ToInt32(tbl, 16);
					string stbl = System.Convert.ToString(itbl, 10);
					string pstbl = stbl.PadLeft(6, '0');
					string tbname = "RO" + pstbl;
					// read in this element from the table.
					rptele = myrodb.RODB_ReadRO(tbname, recid);
					if (rptele != null)
					{
						VlnXmlElement parent;
						string parentid;
						parentid = rptele.GetAttribute("ParentID");
						string rpteleParentid = parentid;
						// walk up tree to get the path through the tree.
						VlnXmlElement child = rptele;
						while (parentid != null && parentid != "00000000")
						{
							parent = myrodb.RODB_ReadRO(tbname, parentid);
							if (parent != null)
							{
								parentid = parent.GetAttribute("ParentID");
								if (parentid == "00000000")
								{
									reversehdrs.Add(parent.InnerText);
									break;
								}
								parent.AppendChild(child);
								child = parent;
								reversehdrs.Add(parent.GetAttribute("MenuTitle"));
							}
							else
								parentid = null;
						}
						// Now hook this into the top part of tree by looking at the table
						// names.  
						VlnXmlElement group = (VlnXmlElement)rootXml.FirstChild;
						while (group != null)
						{
							string curtbname = group.GetAttribute("Table");
							// hook it in here.
							if (curtbname == tbname)
							{
								if (rpteleParentid != "00000000")
									group.AppendChild(child);
								else    // if this is a top group, just reset rept ele
									rptele = group;
								break;
							}
							group = (VlnXmlElement)group.NextSibling;
						}
						// Set up the headers array, it's in reverse order since we walked
						// up the tree, not down.
						int cnt = reversehdrs.Count;
						for (int i = cnt - 1; i >= 0; i--)
							headers.Add(reversehdrs[i]);
						myrodb.MyDBID = tbl;
						rptele.Show(myrodb, headers, showStat, PCChildren); // this will write data to print.tmp file in the RO folder
						Application.DoEvents();
						headers.Clear();
						reversehdrs.Clear();
					}
				}
			}// end foreach roid
			if (showStat != null)
				showStat.Dispose();
			if (showStatBar != null)
				showStatBar.Dispose();
		}
		// C2017-003: use sql
		static public string SqlConnectionStr = null;
		static public SqlConnection ROAPP_SqlConnection
		{
			get
			{
				// Attempt to make a connection 
				SqlConnection cn = new SqlConnection(SqlConnectionStr);
				try
				{
					cn.Open();
					return cn;
				}
				catch (SqlException ex)
				{
					MessageBox.Show(ex.Message, "Could Not Make Connection To Database");
					return null;
				}
			}
		}
		public static string[] PCChildren; //C2021-026 list of Parent/Child Children
		private static string BuildROList(string[] args)
		{
			// when ro's in sql was added, an /sql parameter was introduced to allow the definition of the connection string.  So
			// go through list of args to find the one w/ /f= to find filename that has the ro list in it.
			string roIdArg = null;
			for (int i = 1; i<=args.Length-1; i++)
			{
				string parm2 = args[i];
				if (parm2.StartsWith("/f="))
				{
					FileInfo fi = new FileInfo(parm2.Substring(3));
					using (StreamReader sr = fi.OpenText())
					{
						roIdArg = sr.ReadToEnd();
						sr.Close();
					}
				}
				else if (parm2.StartsWith("/sql="))
				{
					SqlConnectionStr = parm2.Substring(5);
				}
				// C2021-026 get the list of P/C Children if it was passed in
				else if (parm2.ToUpper().StartsWith("/PC="))
					PCChildren = parm2.Substring(4).Split(','); //C2021-026 list of Parent/Child Children
				else
					roIdArg = parm2;
			}
			return roIdArg;
		}
	}
}