// ========================================================================
// Copyright 2007 - Volian Enterprises, Inc. All rights reserved.          
// Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE
// ------------------------------------------------------------------------
// $Workfile: $     $Revision: $                                           
// $Author: $   $Date: $                                                   
//                                                                         
// $History: $                                                             
// ========================================================================
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
namespace VEPROMS.CSLA.Library
{
	public delegate void ItemInfoEvent(object sender);
	/// 
	///	ItemInfo Generated by MyGeneration using the CSLA Object Mapping template
	/// 
	[Serializable()]
	[TypeConverter(typeof(ItemInfoConverter))]
	public partial class ItemInfo : ReadOnlyBase, IDisposable
	{
		public event ItemInfoEvent Changed;
		private void OnChange()
		{
			if (Changed != null) Changed(this);
		}
		#region Log4Net
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		#endregion
		#region Collection
		protected static List _AllList = new List();
		private static Dictionary _AllByPrimaryKey = new Dictionary();
		private static void ConvertListToDictionary()
		{
			List remove = new List();
			foreach (ItemInfo tmp in _AllList)
			{
				_AllByPrimaryKey[tmp.ItemID.ToString()]=tmp; // Primary Key
				remove.Add(tmp);
			}
			foreach (ItemInfo tmp in remove)
				_AllList.Remove(tmp);
		}
		internal static void AddList(ItemInfoList lst)
		{
			foreach (ItemInfo item in lst) _AllList.Add(item);
		}
		public static ItemInfo GetExistingByPrimaryKey(int itemID)
		{
			ConvertListToDictionary();
			string key = itemID.ToString();
			if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key]; 
			return null;
		}
		#endregion
		#region Business Methods
		private string _ErrorMessage = string.Empty;
		public string ErrorMessage
		{
			get { return _ErrorMessage; }
		}
		protected Item _Editable;
		private IVEHasBrokenRules HasBrokenRules
		{
			get
			{
				IVEHasBrokenRules hasBrokenRules = null;
				if (_Editable != null)
					hasBrokenRules = _Editable.HasBrokenRules;
				return hasBrokenRules;
			}
		}
		private int _ItemID;
		[System.ComponentModel.DataObjectField(true, true)]
		public int ItemID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemID",true);
				return _ItemID;
			}
		}
		private int? _PreviousID;
		public int? PreviousID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PreviousID",true);
				if (_MyPrevious != null) _PreviousID = _MyPrevious.ItemID;
				return _PreviousID;
			}
		}
		private ItemInfo _MyPrevious;
		public ItemInfo MyPrevious
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyPrevious",true);
				if (_MyPrevious == null && _PreviousID != null) _MyPrevious = ItemInfo.Get((int)_PreviousID);
				return _MyPrevious;
			}
		}
		private int _ContentID;
		public int ContentID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentID",true);
				if (_MyContent != null) _ContentID = _MyContent.ContentID;
				return _ContentID;
			}
		}
		private ContentInfo _MyContent;
		public ContentInfo MyContent
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyContent",true);
				if (_MyContent == null && _ContentID != 0) _MyContent = ContentInfo.Get(_ContentID);
				return _MyContent;
			}
		}
		private DateTime _DTS = new DateTime();
		public DateTime DTS
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("DTS",true);
				return _DTS;
			}
		}
		private string _UserID = string.Empty;
		public string UserID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("UserID",true);
				return _UserID;
			}
		}
		private int _ItemAnnotationCount = 0;
		/// 
		/// Count of ItemAnnotations for this Item
		/// 
		public int ItemAnnotationCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemAnnotationCount",true);
				return _ItemAnnotationCount;
			}
		}
		private AnnotationInfoList _ItemAnnotations = null;
		[TypeConverter(typeof(AnnotationInfoListConverter))]
		public AnnotationInfoList ItemAnnotations
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemAnnotations",true);
				if (_ItemAnnotationCount > 0 && _ItemAnnotations == null)
					_ItemAnnotations = AnnotationInfoList.GetByItemID(_ItemID);
				return _ItemAnnotations;
			}
		}
		private int _ItemDocVersionCount = 0;
		/// 
		/// Count of ItemDocVersions for this Item
		/// 
		public int ItemDocVersionCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemDocVersionCount",true);
				return _ItemDocVersionCount;
			}
		}
		private DocVersionInfoList _ItemDocVersions = null;
		[TypeConverter(typeof(DocVersionInfoListConverter))]
		public DocVersionInfoList ItemDocVersions
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemDocVersions",true);
				if (_ItemDocVersionCount > 0 && _ItemDocVersions == null)
					_ItemDocVersions = DocVersionInfoList.GetByItemID(_ItemID);
				return _ItemDocVersions;
			}
		}
		private int _NextItemCount = 0;
		/// 
		/// Count of NextItems for this Item
		/// 
		public int NextItemCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("NextItemCount",true);
				return _NextItemCount;
			}
		}
		private ItemInfoList _NextItems = null;
		[TypeConverter(typeof(ItemInfoListConverter))]
		public ItemInfoList NextItems
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("NextItems",true);
				if (_NextItemCount > 0 && _NextItems == null)
					_NextItems = ItemInfoList.GetNext(_ItemID);
				return _NextItems;
			}
		}
		private int _ItemPartCount = 0;
		/// 
		/// Count of ItemParts for this Item
		/// 
		public int ItemPartCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemPartCount",true);
				return _ItemPartCount;
			}
		}
		private PartInfoList _ItemParts = null;
		[TypeConverter(typeof(PartInfoListConverter))]
		public PartInfoList ItemParts
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemParts",true);
				if (_ItemPartCount > 0 && _ItemParts == null)
					_ItemParts = PartInfoList.GetByItemID(_ItemID);
				return _ItemParts;
			}
		}
		private int _ItemTransition_RangeIDCount = 0;
		/// 
		/// Count of ItemTransitions for this Item
		/// 
		public int ItemTransition_RangeIDCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemTransition_RangeIDCount",true);
				return _ItemTransition_RangeIDCount;
			}
		}
		private TransitionInfoList _ItemTransitions_RangeID = null;
		[TypeConverter(typeof(TransitionInfoListConverter))]
		public TransitionInfoList ItemTransitions_RangeID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemTransitions_RangeID",true);
				if (_ItemTransition_RangeIDCount > 0 && _ItemTransitions_RangeID == null)
					_ItemTransitions_RangeID = TransitionInfoList.GetByRangeID(_ItemID);
				return _ItemTransitions_RangeID;
			}
		}
		private int _ItemTransition_ToIDCount = 0;
		/// 
		/// Count of ItemTransitions for this Item
		/// 
		public int ItemTransition_ToIDCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemTransition_ToIDCount",true);
				return _ItemTransition_ToIDCount;
			}
		}
		private TransitionInfoList _ItemTransitions_ToID = null;
		[TypeConverter(typeof(TransitionInfoListConverter))]
		public TransitionInfoList ItemTransitions_ToID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ItemTransitions_ToID",true);
				if (_ItemTransition_ToIDCount > 0 && _ItemTransitions_ToID == null)
					_ItemTransitions_ToID = TransitionInfoList.GetByToID(_ItemID);
				return _ItemTransitions_ToID;
			}
		}
		// TODO: Replace base ItemInfo.ToString function as necessary
		/// 
		/// Overrides Base ToString
		/// 
		/// A string representation of current ItemInfo
		//public override string ToString()
		//{
		//  return base.ToString();
		//}
		// TODO: Check ItemInfo.GetIdValue to assure that the ID returned is unique
		/// 
		/// Overrides Base GetIdValue - Used internally by CSLA to determine equality
		/// 
		/// A Unique ID for the current ItemInfo
		protected override object GetIdValue()
		{
			return _ItemID;
		}
		#endregion
		#region Factory Methods
		private ItemInfo()
		{/* require use of factory methods */
			_AllList.Add(this);
		}
		public void Dispose()
		{
			_AllList.Remove(this);
			_AllByPrimaryKey.Remove(ItemID.ToString());
		}
		public virtual Item Get()
		{
			return _Editable = Item.Get(_ItemID);
		}
		public static void Refresh(Item tmp)
		{
			ItemInfo tmpInfo = GetExistingByPrimaryKey(tmp.ItemID);
			if (tmpInfo == null) return;
			tmpInfo.RefreshFields(tmp);
		}
		private void RefreshFields(Item tmp)
		{
			_PreviousID = tmp.PreviousID;
			_ContentID = tmp.ContentID;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_ItemInfoExtension.Refresh(this);
			_MyPrevious = null;
			_MyContent = null;
			OnChange();// raise an event
		}
		public static void Refresh(ContentItem tmp)
		{
			ItemInfo tmpInfo = GetExistingByPrimaryKey(tmp.ItemID);
			if (tmpInfo == null) return;
			tmpInfo.RefreshFields(tmp);
		}
		private void RefreshFields(ContentItem tmp)
		{
			_PreviousID = tmp.PreviousID;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_ItemInfoExtension.Refresh(this);
			_MyPrevious = null;
			_MyContent = null;
			OnChange();// raise an event
		}
		public static ItemInfo Get(int itemID)
		{
			//if (!CanGetObject())
			//  throw new System.Security.SecurityException("User not authorized to view a Item");
			try
			{
				ItemInfo tmp = GetExistingByPrimaryKey(itemID);
				if (tmp == null)
				{
					tmp = DataPortal.Fetch(new PKCriteria(itemID));
					_AllList.Add(tmp);
				}
				if (tmp.ErrorMessage == "No Record Found") tmp = null;
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on ItemInfo.Get", ex);
			}
		}
		#endregion
		#region Data Access Portal
		internal ItemInfo(SafeDataReader dr)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] ItemInfo.Constructor", GetHashCode());
			try
			{
				ReadData(dr);
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("ItemInfo.Constructor", ex);
				throw new DbCslaException("ItemInfo.Constructor", ex);
			}
		}
		[Serializable()]
		protected class PKCriteria
		{
			private int _ItemID;
			public int ItemID
			{ get { return _ItemID; } }
			public PKCriteria(int itemID)
			{
				_ItemID = itemID;
			}
		}
		private void ReadData(SafeDataReader dr)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] ItemInfo.ReadData", GetHashCode());
			try
			{
				_ItemID = dr.GetInt32("ItemID");
				_PreviousID = (int?)dr.GetValue("PreviousID");
				_ContentID = dr.GetInt32("ContentID");
				_DTS = dr.GetDateTime("DTS");
				_UserID = dr.GetString("UserID");
				_ItemAnnotationCount = dr.GetInt32("AnnotationCount");
				_ItemDocVersionCount = dr.GetInt32("DocVersionCount");
				_NextItemCount = dr.GetInt32("NextCount");
				_ItemPartCount = dr.GetInt32("PartCount");
				_ItemTransition_RangeIDCount = dr.GetInt32("Transition_RangeIDCount");
				_ItemTransition_ToIDCount = dr.GetInt32("Transition_ToIDCount");
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("ItemInfo.ReadData", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("ItemInfo.ReadData", ex);
			}
		}
		private void DataPortal_Fetch(PKCriteria criteria)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] ItemInfo.DataPortal_Fetch", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					ApplicationContext.LocalContext["cn"] = cn;
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "getItem";
						cm.Parameters.AddWithValue("@ItemID", criteria.ItemID);
						using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
						{
							if (!dr.Read())
							{
								_ErrorMessage = "No Record Found";
								return;
							}
							ReadData(dr);
						}
					}
					// removing of item only needed for local data portal
					if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
						ApplicationContext.LocalContext.Remove("cn");
				}
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("ItemInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("ItemInfo.DataPortal_Fetch", ex);
			}
		}
		#endregion
		// Standard Refresh
		#region extension
		ItemInfoExtension _ItemInfoExtension = new ItemInfoExtension();
		[Serializable()]
		partial class ItemInfoExtension : extensionBase {}
		[Serializable()]
		class extensionBase
		{
			// Default Refresh
			public virtual void Refresh(ItemInfo tmp) { }
		}
		#endregion
	} // Class
	#region Converter
	internal class ItemInfoConverter : ExpandableObjectConverter
	{
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
		{
			if (destType == typeof(string) && value is ItemInfo)
			{
				// Return the ToString value
				return ((ItemInfo)value).ToString();
			}
			return base.ConvertTo(context, culture, value, destType);
		}
	}
	#endregion
} // Namespace