// clsHistory.cs
// Copyright (C) 2008 Karel Jordaan karel_jordaan@yahoo.com.au
// 
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

using System;
using System.Runtime.Serialization.Formatters.Binary ;
using System.IO;
using System.Collections;

namespace GUIControlLogic.Persistence
{
	/// <summary>
	/// This class Serialize the searches, results and chat and comparison to binary
	/// </summary>
    /// <remarks>None</remarks>
	public class clsHistory:Error.clsGlobalErr,IDisposable			
	{

		//private clsPersistantSearh[] arSearches;
        /// <summary>
        /// Reference to a binary formatter
        /// </summary>
        /// <remarks>None</remarks>
		private BinaryFormatter formatter = new BinaryFormatter();	

        /// <summary>
        /// User settings class with the information to persist
        /// </summary>
        /// <remarks>None</remarks>
		private  GUIControlLogic.Persistence.clsSettings.SerialOptionsSetting   m_objSettings;

        /// <summary>
        /// Reference to the persistenthistory class
        /// </summary>
        /// <remarks>None</remarks>
		private clsPersistentHistory m_clsPersistentHistory = new clsPersistentHistory ();


		//private clsPersistantResult m_clsPersistantResult = new clsPersistantResult();
		//private clsPersistantSearh m_clsPersistantSearh = new clsPersistantSearh (); 
		private ZANZIClient.clsMain m_clsMain;


        /// <summary>
        /// Constant filename for the presistance file
        /// </summary>
        /// <remarks>send to config file instead of hardcoding</remarks>
		const string XML_FILE ="ZANZIHistory.cvc";

		//	private clsComparison[] arComparison

        /// <summary>
        /// Constructor for the history class
        /// </summary>
        /// <param name="objSettings">A reference to the object that has the settings</param>
        /// <param name="cls">The mdi parent class</param>
		public clsHistory( GUIControlLogic.Persistence.clsSettings.SerialOptionsSetting    objSettings, ZANZIClient.clsMain cls)

			//tree entry
			//'Searches' (count)
			//	>date - searchname {clickable to open}
			//		> 'Results' (count)
			//			>Supplier alias [with chat] {clickable open search}
			//				>chat {clickable to open}
			//'Comparisons'(count)

			
	
		{
			
			try
			{

				m_objSettings = objSettings;

				//Deserialize the text file
				Stream stream = new FileStream(XML_FILE, FileMode.Open, FileAccess.Read, FileShare.None);
				clsPersistentHistory sscls = (clsPersistentHistory)formatter.Deserialize(stream);
				stream.Close();
				
				//m_SerialOptionsSetting = sscls.SOP ;
				//m_SerialMDIFormLocationSetting  = sscls.MDI;
				m_clsPersistentHistory = sscls;

				m_clsMain = cls;
			}

			catch (FileNotFoundException)
			{
				//Do nothing
				//Debug.WriteLine("File not found");
				
			}
			catch (Exception  ex)
			{
				GUIControlLogic.Error.clsExeption exx = new GUIControlLogic.Error.clsExeption(ex);
				//base.ErrByte = 1;
			}
		}

			
		/// <summary>
		/// Loads new forms based on the content of the persistenthistory object
		/// opens the forms in the MDI parent
		/// used for session save 
		/// </summary>
        /// <remarks>None</remarks>
		public void LoadHistory()
		{
			foreach(clsPersistantSearh clsps in m_clsPersistentHistory.arPersistentSearches)
			{
				ZANZIClient.frmSearch   frm = new ZANZIClient.frmSearch(m_clsMain,0);
				//frm.Parent = m_frmMain;
				frm.Name = clsps.objSearch.Name;
				//frm.lstCharacteristics
				frm.m_ResultOneObj  = clsps.objResult.oResult ;
				frm.objSearchCriteria = clsps.objSearch ;
				frm.propertyGrid1.SelectedObject =frm.objSearchCriteria;
				//frm.grdResultOne.DataSource = frm.m_ResultOneObj();

				//frm.Invalidate() ;
				
				frm.Show();
			}

		}
        /// <summary>
        /// Saves the history 
        /// </summary>
        /// <param name="frm">The mdi main form reference</param>
        /// <remarks>None</remarks>
		public void SaveHistory(ZANZIClient.frmMain frm)
		{


			//NOTE you have to cast the datasource of the results datagrid to a arraylist of result one objects

			//check the options frm for the type of saves to perform
			if (m_objSettings.SaveSearch == true)
			{
				m_clsPersistentHistory = new clsPersistentHistory ();

				//interate the child frms for search frms
				foreach (System.Windows.Forms.Form  ffrm in frm.MdiChildren )
				{
					// check name for frmSearch
					if (ffrm.Name.ToString() == "frmSearch")
					{
						//cast mdichild to frmSearch 
						ZANZIClient.frmSearch cls = (ZANZIClient.frmSearch)ffrm;

						//Create a new searh object
						clsPersistantSearh clls = new clsPersistantSearh();
						clls.objSearch = cls.objSearchCriteria;
						//if frmOptions is set to save results do so
						if (m_objSettings.SaveResult == true)
						{
							//Create a new result object
							//clsPersistantResult oResult = new clsPersistantResult();=
							//oResult.objResult = cls.m_ResultOneObj;
							// Add the result to the local search object
							clsPersistantResult pr = new clsPersistantResult();
							pr.oResult  = cls.m_ResultOneObj;
							clls.objResult  = pr;
						}

						//if frmOptions is set to save chats do so
						if (m_objSettings.SaveChat == true)
						{
								
							//clls.objResult.ChatText = cls.m_ResultOneObj.
						}

						//add the object to module level variable
						//reset tbe module level with new object
				
						m_clsPersistentHistory.arPersistentSearches.Add(clls);
					}

					if(ffrm.Name.ToString() == "frmCompare")
					{

					}

				}
			
			}

		}
		
		#region IDisposable Members
		
		/// <summary>
		/// serialize the variables to disk
		/// </summary>
        /// <remarks>None</remarks>
		public void Dispose()
		{
			
			//Serilize the values and text here
			
			//clsPersistentHistory temp = new clsPersistentHistory ();
			//temp.MDI = m_SerialMDIFormLocationSetting ;
			//temp.SOP = m_SerialOptionsSetting;

			Stream stream = new FileStream(XML_FILE, FileMode.Create, FileAccess.Write, FileShare.None);
			formatter.Serialize(stream,m_clsPersistentHistory);
			stream.Close();
		}

		#endregion

		#region clsPersistentHistory class
		/// <summary>
		/// Defines the History object
		/// To display in the history form
		/// </summary>
        /// <remarks>None</remarks>
		[Serializable]
			public class clsPersistentHistory
		{

//			private clsPersistantSearh[] arPersistentSearches;
//			private clsHistoryComparison[] arPersistentComparison; 
			//create two collection base classes instead
			//use XmlElementAttribute.DataType Property
			//search arraylist NEAR serialize

			public clsPersistantArraySearches arPersistentSearches = new clsPersistantArraySearches();
			public ArrayList arPersistentComparison = new ArrayList(); 

		}

			#endregion

		#region clsPersistantArraySearches collection 
        /// <summary>
        /// Collection of searches
        /// </summary>
        /// <remarks>None</remarks>
		[Serializable]
		public class clsPersistantArraySearches : ArrayList		
		{
			public int Add( clsPersistantSearh value )  
			{
				return( base.Add( value ) );
			}

			public  clsPersistantSearh this[ int index ]  
			{
				get  
				{
					return( (clsPersistantSearh) base[index] );
				}
				set  
				{
					base[index] = value;
				}
			}
		}



//		public class clsPersistantArraySearches : CollectionBase  
//		{
//
//			public clsPersistantSearh this[ int index ]  
//			{
//				get  
//				{
//					return( (clsPersistantSearh) List[index] );
//				}
//				set  
//				{
//					List[index] = value;
//				}
//			}
//
//			public int Add( clsPersistantSearh value )  
//			{
//				return( List.Add( value ) );
//			}
//
//			public int IndexOf( clsPersistantSearh value )  
//			{
//				return( List.IndexOf( value ) );
//			}
//
//			public void Insert( int index, clsPersistantSearh value )  
//			{
//				List.Insert( index, value );
//			}
//
//			public void Remove( clsPersistantSearh value )  
//			{
//				List.Remove( value );
//			}
//
//			public bool Contains( clsPersistantSearh value )  
//			{
//				// If value is not of type Int16, this will return false.
//				return( List.Contains( value ) );
//			}
//
//			protected override void OnInsert( int index, Object value )  
//			{
//				// Insert additional code to be run only when inserting values.
//			}
//
//			protected override void OnRemove( int index, Object value )  
//			{
//				// Insert additional code to be run only when removing values.
//			}
//
//			protected override void OnSet( int index, Object oldValue, Object newValue )  
//			{
//				// Insert additional code to be run only when setting values.
//			}
//
//			//			protected override void OnValidate( Object value )  
//			//			{
//			//				if ( value.GetType() != Type.GetType("System.Int16") )
//			//					throw new ArgumentException( "value must be of type Int16.", "value" );
//			//			}
//
//		}

		#endregion

		#region clsPersistantSearh class

		/// <summary>
		/// Defines the extended search object
		/// To display in the history form
		/// </summary>
        /// <remarks>None</remarks>
		[Serializable]
		public class clsPersistantSearh
		{

			private System.DateTime  dateTime;
			public ZANZILib.Protocols.QueryCriteria.clsZanziProt  objSearch;
			public clsPersistantResult objResult; 
			//to make the creation of the tree faster
			public string Name;

		}

		#endregion

		#region clsPersistantResult class
		/// <summary>
		/// Defines the extended result object
		/// To display in the history form
		/// </summary>
        /// <remarks>None</remarks>
		[Serializable]
		public class clsPersistantResult
		{

			public string ChatText;
			public ZANZILib.Protocols.ResultOne.clsZanziProtResultOne  oResult;

		}
		

		#endregion

		#region clsHistoryComparison class
		/// <summary>
		/// A single class to hold the collection of comparison
		/// </summary>
        /// <remarks>None</remarks>
		public class clsHistoryComparison
		{

		}
	
	#endregion
	}


	}