// ========================================================================
// 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 PermissionInfoEvent(object sender);
	/// 
	///	PermissionInfo Generated by MyGeneration using the CSLA Object Mapping template
	/// 
	[Serializable()]
	[TypeConverter(typeof(PermissionInfoConverter))]
	public partial class PermissionInfo : ReadOnlyBase, IDisposable
	{
		public event PermissionInfoEvent 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
		private static List _CacheList = new List();
		protected static void AddToCache(PermissionInfo permissionInfo)
		{
			if (!_CacheList.Contains(permissionInfo)) _CacheList.Add(permissionInfo); // In AddToCache
		}
		protected static void RemoveFromCache(PermissionInfo permissionInfo)
		{
			while (_CacheList.Contains(permissionInfo)) _CacheList.Remove(permissionInfo); // In RemoveFromCache
		}
		private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
		private static void ConvertListToDictionary()
		{
			List remove = new List();
			foreach (PermissionInfo tmp in _CacheList)
			{
				if (!_CacheByPrimaryKey.ContainsKey(tmp.PID.ToString()))
				{
					_CacheByPrimaryKey[tmp.PID.ToString()] = new List(); // Add new list for PrimaryKey
				}
				_CacheByPrimaryKey[tmp.PID.ToString()].Add(tmp); // Add to Primary Key list
				remove.Add(tmp);
			}
			foreach (PermissionInfo tmp in remove)
				RemoveFromCache(tmp);
		}
		internal static void AddList(PermissionInfoList lst)
		{
			foreach (PermissionInfo item in lst) AddToCache(item);
		}
		protected static PermissionInfo GetCachedByPrimaryKey(int pid)
		{
			ConvertListToDictionary();
			string key = pid.ToString();
			if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0];
			return null;
		}
		#endregion
		#region Business Methods
		private string _ErrorMessage = string.Empty;
		public string ErrorMessage
		{
			get { return _ErrorMessage; }
		}
		protected Permission _Editable;
		private IVEHasBrokenRules HasBrokenRules
		{
			get
			{
				IVEHasBrokenRules hasBrokenRules = null;
				if (_Editable != null)
					hasBrokenRules = _Editable.HasBrokenRules;
				return hasBrokenRules;
			}
		}
		private int _PID;
		[System.ComponentModel.DataObjectField(true, true)]
		public int PID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PID", true);
				return _PID;
			}
		}
		private int _RID;
		public int RID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("RID", true);
				if (_MyRole != null) _RID = _MyRole.RID;
				return _RID;
			}
		}
		private RoleInfo _MyRole;
		public RoleInfo MyRole
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyRole", true);
				if (_MyRole == null && _RID != 0) _MyRole = RoleInfo.Get(_RID);
				return _MyRole;
			}
		}
		private int _PermLevel;
		/// 
		/// 0 - None, 1 - Security, 2 - System, 3 - RO, 4 - Procdures, 5 - Sections, 6 - Steps, 7 - Comments
		/// 
		public int PermLevel
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PermLevel", true);
				return _PermLevel;
			}
		}
		private int _VersionType;
		/// 
		/// 0 - None, 1 - Working Draft, 2 - Approved, (3 - All)
		/// 
		public int VersionType
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("VersionType", true);
				return _VersionType;
			}
		}
		private int _PermValue;
		/// 
		/// 1 - Read, 2 - Write, 4 - Create, 8 - Delete (15 - All)
		/// 
		public int PermValue
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PermValue", true);
				return _PermValue;
			}
		}
		private int _PermAD;
		/// 
		/// 0 - Allow, 1 - Deny
		/// 
		public int PermAD
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PermAD", true);
				return _PermAD;
			}
		}
		private string _StartDate = string.Empty;
		public string StartDate
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("StartDate", true);
				return _StartDate;
			}
		}
		private string _EndDate = string.Empty;
		public string EndDate
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("EndDate", true);
				return _EndDate;
			}
		}
		private string _Config = string.Empty;
		public string Config
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Config", true);
				return _Config;
			}
		}
		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 _UsrID = string.Empty;
		public string UsrID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("UsrID", true);
				return _UsrID;
			}
		}
		// TODO: Replace base PermissionInfo.ToString function as necessary
		/// 
		/// Overrides Base ToString
		/// 
		/// A string representation of current PermissionInfo
		//public override string ToString()
		//{
		//  return base.ToString();
		//}
		// TODO: Check PermissionInfo.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 PermissionInfo
		protected override object GetIdValue()
		{
			return _PID;
		}
		#endregion
		#region Factory Methods
		private static int _PermissionInfoUnique = 0;
		private static int PermissionInfoUnique
		{ get { return ++_PermissionInfoUnique; } }
		private int _MyPermissionInfoUnique = PermissionInfoUnique;
		public int MyPermissionInfoUnique
		{ get { return _MyPermissionInfoUnique; } }
		protected PermissionInfo()
		{/* require use of factory methods */
			AddToCache(this);
		}
		public void Dispose()
		{
			RemoveFromCache(this);
			if (!_CacheByPrimaryKey.ContainsKey(PID.ToString())) return;
			List listPermissionInfo = _CacheByPrimaryKey[PID.ToString()]; // Get the list of items
			while (listPermissionInfo.Contains(this)) listPermissionInfo.Remove(this); // Remove the item from the list
			if (listPermissionInfo.Count == 0) // If there are no items left in the list
				_CacheByPrimaryKey.Remove(PID.ToString()); // remove the list
		}
		public virtual Permission Get()
		{
			return _Editable = Permission.Get(_PID);
		}
		public static void Refresh(Permission tmp)
		{
			string key = tmp.PID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (PermissionInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(Permission tmp)
		{
			if (_RID != tmp.RID)
			{
				if (MyRole != null) MyRole.RefreshRolePermissions(); // Update List for old value
				_RID = tmp.RID; // Update the value
			}
			_MyRole = null; // Reset list so that the next line gets a new list
			if (MyRole != null) MyRole.RefreshRolePermissions(); // Update List for new value
			_PermLevel = tmp.PermLevel;
			_VersionType = tmp.VersionType;
			_PermValue = tmp.PermValue;
			_PermAD = tmp.PermAD;
			_StartDate = tmp.StartDate;
			_EndDate = tmp.EndDate;
			_Config = tmp.Config;
			_DTS = tmp.DTS;
			_UsrID = tmp.UsrID;
			_PermissionInfoExtension.Refresh(this);
			if(_MyRole != null)
			{
				_MyRole.Dispose();// Dispose related value
				_MyRole = null;// Reset related value
			}
			OnChange();// raise an event
		}
		public static void Refresh(RolePermission tmp)
		{
			string key = tmp.PID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (PermissionInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(RolePermission tmp)
		{
			_PermLevel = tmp.PermLevel;
			_VersionType = tmp.VersionType;
			_PermValue = tmp.PermValue;
			_PermAD = tmp.PermAD;
			_StartDate = tmp.StartDate;
			_EndDate = tmp.EndDate;
			_Config = tmp.Config;
			_DTS = tmp.DTS;
			_UsrID = tmp.UsrID;
			_PermissionInfoExtension.Refresh(this);
			if(_MyRole != null)
			{
				_MyRole.Dispose();// Dispose related value
				_MyRole = null;// Reset related value
			}
			OnChange();// raise an event
		}
		public static PermissionInfo Get(int pid)
		{
			//if (!CanGetObject())
			//  throw new System.Security.SecurityException("User not authorized to view a Permission");
			try
			{
				PermissionInfo tmp = GetCachedByPrimaryKey(pid);
				if (tmp == null)
				{
					tmp = DataPortal.Fetch(new PKCriteria(pid));
					AddToCache(tmp);
				}
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up PermissionInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on PermissionInfo.Get", ex);
			}
		}
		#endregion
		#region Data Access Portal
		internal PermissionInfo(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PermissionInfo.Constructor", GetHashCode());
			try
			{
				ReadData(dr);
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("PermissionInfo.Constructor", ex);
				throw new DbCslaException("PermissionInfo.Constructor", ex);
			}
		}
		[Serializable()]
		protected class PKCriteria
		{
			private int _PID;
			public int PID
			{ get { return _PID; } }
			public PKCriteria(int pid)
			{
				_PID = pid;
			}
		}
		private void ReadData(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PermissionInfo.ReadData", GetHashCode());
			try
			{
				_PID = dr.GetInt32("PID");
				_RID = dr.GetInt32("RID");
				_PermLevel = dr.GetInt32("PermLevel");
				_VersionType = dr.GetInt32("VersionType");
				_PermValue = dr.GetInt32("PermValue");
				_PermAD = dr.GetInt32("PermAD");
				_StartDate = dr.GetSmartDate("StartDate").Text;
				_EndDate = dr.GetSmartDate("EndDate").Text;
				_Config = dr.GetString("Config");
				_DTS = dr.GetDateTime("DTS");
				_UsrID = dr.GetString("UsrID");
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("PermissionInfo.ReadData", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("PermissionInfo.ReadData", ex);
			}
		}
		private void DataPortal_Fetch(PKCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PermissionInfo.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 = "getPermission";
						cm.Parameters.AddWithValue("@PID", criteria.PID);
						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("PermissionInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("PermissionInfo.DataPortal_Fetch", ex);
			}
		}
		#endregion
		// Standard Refresh
		#region extension
		PermissionInfoExtension _PermissionInfoExtension = new PermissionInfoExtension();
		[Serializable()]
		partial class PermissionInfoExtension : extensionBase { }
		[Serializable()]
		class extensionBase
		{
			// Default Refresh
			public virtual void Refresh(PermissionInfo tmp) { }
		}
		#endregion
	} // Class
	#region Converter
	internal class PermissionInfoConverter : ExpandableObjectConverter
	{
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
		{
			if (destType == typeof(string) && value is PermissionInfo)
			{
				// Return the ToString value
				return ((PermissionInfo)value).ToString();
			}
			return base.ConvertTo(context, culture, value, destType);
		}
	}
	#endregion
} // Namespace