/*********************************************************************************************
 * Copyright 2004 - Volian Enterprises, Inc. All rights reserved.
 * Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE
 * ------------------------------------------------------------------------------
 * $Workfile: ARProperties.cs $     $Revision: 2 $
 * $Author: Jsj $   $Date: 8/20/04 4:45p $
 *
 * $History: ARProperties.cs $
 * 
 * *****************  Version 2  *****************
 * User: Jsj          Date: 8/20/04    Time: 4:45p
 * Updated in $/LibSource/VEObject
 * fixed cancel of archive selected procedures
 * 
 * *****************  Version 1  *****************
 * User: Kathy        Date: 7/27/04    Time: 8:52a
 * Created in $/LibSource/VEObject
 *********************************************************************************************/
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;
using System.Data;
using VDB_Set;
using Utils;
namespace VEObject
{
	/// 
	/// NOTE: cmbType (the combo box that contains the document types) must match
	///  the order of document types given in the ArchiveTypeOptions for this dialog
	///  to work correctly
	/// 
	
	public class ARProperties : System.Windows.Forms.Form
	{
		private System.Windows.Forms.PropertyGrid myPropertyGrid;
		private System.Windows.Forms.ComboBox cmbType;
		private System.Windows.Forms.Label lblType;
		private System.Windows.Forms.Button btnOK;
		private System.Windows.Forms.Button btnCancel;
		private System.Windows.Forms.Button btnApply;
		private VEO_Base _ParentObj;
		private VEO_Base _CurObj;
		private bool isnew;
		private bool glbCancel;
		private bool zipInCurProcSet;
		private bool hasInvalidEntry;
		private string strCurZipPath;
		private string strZipFileName;
		private string strFilesToArchive;
		private string strZipFileExcludeList;
		private string strProcSetDir;
		private ZipFuncs ZipFile;
		/// 
		/// Required designer variable.
		/// 
		private System.ComponentModel.Container components = null;
		public ARProperties(Object parent, Object curobj)
		{
			//
			// Required for Windows Form Designer support
			//
			_ParentObj = (VEO_Base) parent;
			_CurObj = (VEO_Base) curobj;
			VEO_Archive tmpArc = (VEO_Archive)curobj;
			if (tmpArc.isnew == true)
				isnew=true;
			else
				isnew=false;
			InitializeComponent();
			this.myPropertyGrid.SelectedObject=curobj;
			strCurZipPath = _ParentObj._Location;
			strProcSetDir = _ParentObj._Location;
			// If new, combo box should have 'Full'
			this.cmbType.Visible=false;
			this.btnApply.Enabled=false;
			glbCancel = false;
			zipInCurProcSet = true;
			if (isnew == true)
			{
				this.btnApply.Visible = false;
				SetupNewFileName();
				ZipFile = new ZipFuncs();
				// Since this a new Zip File, don't assign ZipFile with the path/name,
				// Title, or Comment.  These values can be changed prior to the
				// actual creation of the Zip file.
			}
			else
			{
				VEO_Archive arc = (VEO_Archive)curobj;
				ZipFile = new ZipFuncs(arc._Location);
				GetCommentInformation();
				this.cmbType.SelectedIndex = (int) arc._ArchiveType;
			}
		}
		private void SetupNewFileName()
		{
			int i=0;
			StringBuilder newname = new StringBuilder();
			
			VEO_Archive arc = (VEO_Archive) _CurObj;
			// The old VE-PROMS logic would create SOURCE.ZIP for
			// the first archive, then ARCH_xxx.ZIP for the rest.
			// Now we will just create ARCH_xxx.ZIP
			while(i==0 || arc.Exists(strCurZipPath + "\\" + newname.ToString()))
			{
				newname.Remove(0,newname.Length);
				newname.Append("ARCH_");
				newname.Append(i.ToString("d3"));
				newname.Append(".ZIP");
				i++;
			}
			strZipFileName = newname.ToString();
			_CurObj._Location = strCurZipPath + "\\" + strZipFileName;
			_CurObj._Title = "New Archive " + newname.ToString();
			this.myPropertyGrid.SelectedObject=_CurObj;
		}
		/// 
		/// 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()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ARProperties));
			this.myPropertyGrid = new System.Windows.Forms.PropertyGrid();
			this.cmbType = new System.Windows.Forms.ComboBox();
			this.lblType = new System.Windows.Forms.Label();
			this.btnOK = new System.Windows.Forms.Button();
			this.btnCancel = new System.Windows.Forms.Button();
			this.btnApply = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// myPropertyGrid
			// 
			this.myPropertyGrid.CommandsVisibleIfAvailable = true;
			this.myPropertyGrid.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.myPropertyGrid.HelpVisible = false;
			this.myPropertyGrid.LargeButtons = false;
			this.myPropertyGrid.LineColor = System.Drawing.SystemColors.ScrollBar;
			this.myPropertyGrid.Location = new System.Drawing.Point(0, 48);
			this.myPropertyGrid.Name = "myPropertyGrid";
			this.myPropertyGrid.Size = new System.Drawing.Size(736, 112);
			this.myPropertyGrid.TabIndex = 2;
			this.myPropertyGrid.Text = "Properties";
			this.myPropertyGrid.ToolbarVisible = false;
			this.myPropertyGrid.ViewBackColor = System.Drawing.SystemColors.Window;
			this.myPropertyGrid.ViewForeColor = System.Drawing.SystemColors.WindowText;
			this.myPropertyGrid.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.myPropertyGrid_PropertyValueChanged);
			// 
			// cmbType
			// 
			this.cmbType.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.cmbType.Items.AddRange(new object[] {
														 "Full",
														 "Partial"});
			this.cmbType.Location = new System.Drawing.Point(104, 0);
			this.cmbType.Name = "cmbType";
			this.cmbType.Size = new System.Drawing.Size(208, 24);
			this.cmbType.TabIndex = 3;
			this.cmbType.SelectedIndexChanged += new System.EventHandler(this.cmbType_SelectedIndexChanged);
			// 
			// lblType
			// 
			this.lblType.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.lblType.Location = new System.Drawing.Point(0, 0);
			this.lblType.Name = "lblType";
			this.lblType.Size = new System.Drawing.Size(96, 24);
			this.lblType.TabIndex = 4;
			this.lblType.Text = "Archive Type:";
			this.lblType.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
			// 
			// btnOK
			// 
			this.btnOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.btnOK.Location = new System.Drawing.Point(432, 200);
			this.btnOK.Name = "btnOK";
			this.btnOK.Size = new System.Drawing.Size(64, 24);
			this.btnOK.TabIndex = 8;
			this.btnOK.Text = "OK";
			this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
			// 
			// btnCancel
			// 
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.btnCancel.Location = new System.Drawing.Point(512, 200);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.Size = new System.Drawing.Size(64, 24);
			this.btnCancel.TabIndex = 9;
			this.btnCancel.Text = "Cancel";
			this.btnCancel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
			// 
			// btnApply
			// 
			this.btnApply.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.btnApply.Location = new System.Drawing.Point(592, 200);
			this.btnApply.Name = "btnApply";
			this.btnApply.Size = new System.Drawing.Size(56, 24);
			this.btnApply.TabIndex = 10;
			this.btnApply.Text = "Apply";
			this.btnApply.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			this.btnApply.Click += new System.EventHandler(this.btnApply_Click);
			// 
			// ARProperties
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.CausesValidation = false;
			this.ClientSize = new System.Drawing.Size(736, 246);
			this.Controls.Add(this.btnApply);
			this.Controls.Add(this.btnCancel);
			this.Controls.Add(this.btnOK);
			this.Controls.Add(this.lblType);
			this.Controls.Add(this.cmbType);
			this.Controls.Add(this.myPropertyGrid);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "ARProperties";
			this.Text = "Archive Properties";
			this.ResumeLayout(false);
		}
		#endregion
		private void cmbType_SelectedIndexChanged(object sender, System.EventArgs e)
		{
		}
		// save was clicked, use the objects save methods.
		private void btnOK_Click(object sender, System.EventArgs e)
		{
			btnApply_Click(sender,e);
			if (hasInvalidEntry)
			{
				DialogResult = DialogResult.None;
				return; // keep the dialog open
			}
			if (!glbCancel)
				DialogResult=DialogResult.OK;
			else
				DialogResult=DialogResult.Cancel;
			this.Close();
		}
		// Apply changes
		private void btnApply_Click(object sender, System.EventArgs e)
		{
			bool success = true;
			if (!ValidatePropertyEntries()) // check the entry fields
			{
				return; // has invalid data in a property field
			}
			
			if (isnew)
			{
				if(_ParentObj==null)
				{
					DialogResult=DialogResult.Cancel;
					return;
				}
				// generate new zip file
				success = GenerateArchiveFile();
				if (success)
				{
				// save the property values
					success=_CurObj.Write();
				}
			}
			else // update existing ZipFile's Comment Field
			{
				success=_CurObj.Write();
				if (success)
					success = AddCommentInformation();
			}
			// if not successful with the archive, set the cancel
			// flag so that a false tree item does not appear.
			// Note that when archiving outside of the current directory,
			// (for example to a floppy disk), success is set to false to
			// prevent a false tree item.
			glbCancel = !success;
			btnApply.Enabled=false;
		}
		private bool SelectProcsToArchive()
		{
			StringCollection SelectedFilesToArchive;
			bool isfirst = true;
			bool rtnval = false;
			ProcedureSelectionList ProcList = new ProcedureSelectionList();
			vdb_Set vdbSet=new vdb_Set(strProcSetDir + "\\SET.DBF");
			// Loop thru the procset (process like a dataset)
			DataTable tbl = vdbSet.DB_Data.Tables[0];
			foreach (DataRow row in tbl.Rows)
			{
				// skip the first one (it's always a "blank" record)
				if (isfirst)
					isfirst = false;
				else
				{
					ProcList.Add(row);
				}
			}
			if (ProcList.ShowDialog() == DialogResult.OK)
			{
				StringBuilder tmpstr = new StringBuilder();
				string strZipPath = "\"" + strProcSetDir + "\\";
				// get list of procedures to archive
				// Note that there is no file extension in this list of dBase files
				SelectedFilesToArchive = ProcList.GetListOfSelectedProcs_Files();
				for(int j=0; j 0)
					rtnval = true;
			}
            return rtnval;
		}
		// This function generates a new zip file
		private bool GenerateArchiveFile()
		{
			bool rtnval = true;
			StringBuilder cmntTxt = new StringBuilder();
			VEO_Archive arc = (VEO_Archive) _CurObj;
			this.glbCancel = false;
			if (arc._ArchiveType == VEO_Base.ArchiveTypeOptions.Partial)
			{
				// get list of selected procedures to archive
				rtnval = SelectProcsToArchive();
			}
			else
			{
				// Archive entire procedure directory
				strFilesToArchive = "\"" + strProcSetDir + "\\*.*\"";
			}
			if (rtnval)
			{
				strZipFileExcludeList = "\"" + strProcSetDir + "\\Approved\\*.*\" \"" + strProcSetDir + "\\Temps\\*.*\" *.zip process.dat ?process.dat *.lck";
				// Setup DynaZip
				ZipFile.strZipPathAndFile = arc.Location;
				ZipFile.strZipFileExcludeList = strZipFileExcludeList;
				ZipFile.strFilesToArchive = strFilesToArchive;
				ZipFile.strArcTitle = arc.Description;
				ZipFile.strComment = arc.Comment;
				ZipFile.ArchiveType = (int)arc._ArchiveType;
				this.Enabled = false;
				rtnval = ZipFile.CreateNewZipFile();
				this.Enabled = true;
			}
	
			return rtnval;
		}
		private bool AddCommentInformation()
		{
			VEO_Archive arc = (VEO_Archive) _CurObj;
			// add comment
			ZipFile.strArcTitle = arc.Description;
			ZipFile.ArchiveType = (int)arc._ArchiveType;
			ZipFile.strComment = arc.Comment;
			return ZipFile.AddZipCommentInformation();
		}
		private void GetCommentInformation()
		{
			this.glbCancel = false;
			VEO_Archive arc = (VEO_Archive) _CurObj;
			if (ZipFile.strArcTitle == null)
				arc.Description = arc._Title;
			else
				arc.Description = ZipFile.strArcTitle;
			arc.Comment = ZipFile.strComment;
			if (ZipFile.ArchiveType == (int)VEO_Base.ArchiveTypeOptions.Full)
				arc.ArchiveType = VEO_Base.ArchiveTypeOptions.Full;
			else
				arc.ArchiveType = VEO_Base.ArchiveTypeOptions.Partial;
			arc.Write();
			return;
		}
		private void myPropertyGrid_PropertyValueChanged(object s, System.Windows.Forms.PropertyValueChangedEventArgs e)
		{
			btnApply.Enabled = true;
		}
		private void btnCancel_Click(object sender, System.EventArgs e)
		{
			this.glbCancel = true;
		}
		/*
		 * Check the property fields for invalid entries
		 * If an invalid entry is found, display a message and
		 * return to the property dialog
		 */
		private bool ValidatePropertyEntries()
		{
			VEO_Archive arc = (VEO_Archive) _CurObj;
			hasInvalidEntry = false;
			// Check the zip file path and filename
			if (!IsAValidZipFileLocation())
			{
				hasInvalidEntry = true;
				return false; // data in fields are not valid
			}
			 if (zipInCurProcSet && (arc.Description == null || arc.Description.Equals("")))
			{
				// put in a default title
				arc.Description = "Archive: " + strZipFileName;
			}
			return (true); // data in fields are valid
		}
		/*
		 * Check the zip file name and path.
		 * Display message box to notify user of invalid entry.
		 * Assign local strArchive variables accordingly.
		 */
		private bool IsAValidZipFileLocation()
		{
			string strArchiveLocation;
			string strCurDirSave;
			VEO_Archive arc = (VEO_Archive) _CurObj;			
			strArchiveLocation = arc._Location;
			// Check for a cleared out location field
			if (arc._Location == null || arc._Location.Equals(""))
			{
				MessageBox.Show("Need to Enter the Archive Location and File Name","Archive Error");
				return false;
			}
			string strTmp = strArchiveLocation.ToUpper();
			// Check for a zip extension
			if (!strTmp.EndsWith(".ZIP"))
			{
				MessageBox.Show("Need to enter the Archive File Name","Archive Error");
				return false;
			}
			// make sure the current working directory is the current procedure set
			strCurDirSave = Directory.GetCurrentDirectory();
			Directory.SetCurrentDirectory(strProcSetDir);
			// Get the full path based on the user entry
			strArchiveLocation = Path.GetFullPath(strArchiveLocation);
			if (!strArchiveLocation.Equals(arc._Location))
			{
				if (strArchiveLocation == null || strArchiveLocation.Equals(""))
				{
					MessageBox.Show("Invalid Archive File Name or File Path","Archive Error");
					// reset the current working directory
					Directory.SetCurrentDirectory(strCurDirSave);
					return false;
				}
				arc._Location = strArchiveLocation;
			}
			// parse out the file name
			strZipFileName = Path.GetFileName(strArchiveLocation);
			// parse out the path
			strCurZipPath = strArchiveLocation.Substring(0,strArchiveLocation.LastIndexOf(strZipFileName)-1);
			// If the zip file path is not the same as the current working directory
			// then flag the fact we are creating a zip file outside the procedure directory.
			zipInCurProcSet = Directory.Equals(Directory.GetCurrentDirectory(),strCurZipPath);
			// reset the current working directory
			Directory.SetCurrentDirectory(strCurDirSave);
			return true;
		}
	}
}