// ========================================================================
// 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 RevisionInfoEvent(object sender);
    /// 
    ///	RevisionInfo Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(RevisionInfoConverter))]
    public partial class RevisionInfo : ReadOnlyBase, IDisposable
    {
        public event RevisionInfoEvent 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(RevisionInfo revisionInfo)
        {
            if (!_CacheList.Contains(revisionInfo)) _CacheList.Add(revisionInfo); // In AddToCache
        }
        protected static void RemoveFromCache(RevisionInfo revisionInfo)
        {
            while (_CacheList.Contains(revisionInfo)) _CacheList.Remove(revisionInfo); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            while (_CacheList.Count > 0) // Move RevisionInfo(s) from temporary _CacheList to _CacheByPrimaryKey
            {
                RevisionInfo tmp = _CacheList[0]; // Get the first RevisionInfo
                string pKey = tmp.RevisionID.ToString();
                if (!_CacheByPrimaryKey.ContainsKey(pKey))
                {
                    _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey
                }
                _CacheByPrimaryKey[pKey].Add(tmp); // Add to Primary Key list
                _CacheList.RemoveAt(0); // Remove the first RevisionInfo
            }
        }
        internal static void AddList(RevisionInfoList lst)
        {
            foreach (RevisionInfo item in lst) AddToCache(item);
        }
        protected static RevisionInfo GetCachedByPrimaryKey(int revisionID)
        {
            ConvertListToDictionary();
            string key = revisionID.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 Revision _Editable;
        private IVEHasBrokenRules HasBrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = null;
                if (_Editable != null)
                    hasBrokenRules = _Editable.HasBrokenRules;
                return hasBrokenRules;
            }
        }
        private int _RevisionID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int RevisionID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _RevisionID;
            }
        }
        private int _ItemID;
        public int ItemID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ItemID;
            }
        }
        private int _TypeID;
        public int TypeID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _TypeID;
            }
        }
        private string _RevisionNumber = string.Empty;
        public string RevisionNumber
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _RevisionNumber;
            }
        }
        private DateTime? _RevisionDate;
        public DateTime? RevisionDate
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _RevisionDate;
            }
        }
        private string _Notes = string.Empty;
        public string Notes
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _Notes;
            }
        }
        private string _Config = string.Empty;
        public string Config
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _Config;
            }
        }
        private DateTime _DTS = new DateTime();
        public DateTime DTS
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DTS;
            }
        }
        private string _UserID = string.Empty;
        public string UserID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _UserID;
            }
        }
        private int _RevisionCheckCount = 0;
        /// 
        /// Count of RevisionChecks for this Revision
        /// 
        public int RevisionCheckCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_RevisionCheckCount < 0)
                    _RevisionCheckCount = RevisionChecks.Count;
                return _RevisionCheckCount;
            }
        }
        private CheckInfoList _RevisionChecks = null;
        [TypeConverter(typeof(CheckInfoListConverter))]
        public CheckInfoList RevisionChecks
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_RevisionCheckCount < 0 || (_RevisionCheckCount > 0 && _RevisionChecks == null))
                    _RevisionChecks = CheckInfoList.GetByRevisionID(_RevisionID);
                if (_RevisionCheckCount < 0)
                    _RevisionCheckCount = _RevisionChecks.Count;
                return _RevisionChecks;
            }
        }
        public void RefreshRevisionChecks()
        {
            _RevisionCheckCount = -1;
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_RevisionID.ToString()))
                foreach (RevisionInfo tmp in _CacheByPrimaryKey[_RevisionID.ToString()])
                    tmp._RevisionCheckCount = -1; // This will cause the data to be requeried
        }
        private int _RevisionVersionCount = 0;
        /// 
        /// Count of RevisionVersions for this Revision
        /// 
        public int RevisionVersionCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                //_MyLog.WarnFormat("RevisionVersionCount 1 - {0}", GC.GetTotalMemory(true));
                if (_RevisionVersionCount < 0)
                {
                    _RevisionVersionCount = RevisionVersions.Count;
                    //_MyLog.WarnFormat("RevisionVersionCount 2 (after setting count) - {0}", GC.GetTotalMemory(true));
                }
                //_MyLog.WarnFormat("RevisionVersionCount 3 (before return) - {0}", GC.GetTotalMemory(true));
                return _RevisionVersionCount;
            }
        }
        private VersionInfoList _RevisionVersions = null;
        [TypeConverter(typeof(VersionInfoListConverter))]
        public VersionInfoList RevisionVersions
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                //_MyLog.WarnFormat("RevisionVersions 1 - {0}", GC.GetTotalMemory(true));
                if (_RevisionVersionCount < 0 || (_RevisionVersionCount > 0 && _RevisionVersions == null))
                {
                    //_MyLog.WarnFormat("RevisionVersions 2 (before using) - {0}  count {1}", GC.GetTotalMemory(true),_RevisionVersionCount);
                    using (VersionInfoList vil = VersionInfoList.GetByRevisionID(_RevisionID))
                    {
                        //_MyLog.WarnFormat("RevisionVersions 3 (using) - {0}", GC.GetTotalMemory(true));
                        _RevisionVersions = vil;
                    }
                }
                //_MyLog.WarnFormat("RevisionVersions 4 (after using) - {0}", GC.GetTotalMemory(true));
                if (_RevisionVersionCount < 0)
                {
                    _RevisionVersionCount = _RevisionVersions.Count;
                    //_MyLog.WarnFormat("RevisionVersions 4 (after setting count) - {0}", GC.GetTotalMemory(true));
                }
                //_MyLog.WarnFormat("RevisionVersions 5 (before return) - {0}", GC.GetTotalMemory(true));
                return _RevisionVersions;
            }
        }
        public void RefreshRevisionVersions()
        {
            _RevisionVersionCount = -1;
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_RevisionID.ToString()))
                foreach (RevisionInfo tmp in _CacheByPrimaryKey[_RevisionID.ToString()])
                    tmp._RevisionVersionCount = -1; // This will cause the data to be requeried
        }
        // CSLATODO: Replace base RevisionInfo.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current RevisionInfo
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // CSLATODO: Check RevisionInfo.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 RevisionInfo
        protected override object GetIdValue()
        {
            return MyRevisionInfoUnique; // Absolutely Unique ID
        }
        #endregion
        #region Factory Methods
        private static int _RevisionInfoUnique = 0;
        private static int RevisionInfoUnique
        { get { return ++_RevisionInfoUnique; } }
        private int _MyRevisionInfoUnique = RevisionInfoUnique;
        public int MyRevisionInfoUnique // Absolutely Unique ID - Info
        { get { return _MyRevisionInfoUnique; } }
        protected RevisionInfo()
        {/* require use of factory methods */
            AddToCache(this);
        }
        private bool _Disposed = false;
        private static int _CountCreated = 0;
        private static int _CountDisposed = 0;
        private static int _CountFinalized = 0;
        private static int IncrementCountCreated
        { get { return ++_CountCreated; } }
        private int _CountWhenCreated = IncrementCountCreated;
        public static int CountCreated
        { get { return _CountCreated; } }
        public static int CountNotDisposed
        { get { return _CountCreated - _CountDisposed; } }
        public static int CountNotFinalized
        { get { return _CountCreated - _CountFinalized; } }
        ~RevisionInfo()
        {
            _CountFinalized++;
        }
        public void Dispose()
        {
            if (_Disposed) return;
            _CountDisposed++;
            _Disposed = true;
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(RevisionID.ToString())) return;
            List listRevisionInfo = _CacheByPrimaryKey[RevisionID.ToString()]; // Get the list of items
            while (listRevisionInfo.Contains(this)) listRevisionInfo.Remove(this); // Remove the item from the list
            if (listRevisionInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(RevisionID.ToString()); // remove the list
        }
        public virtual Revision Get()
        {
            return _Editable = Revision.Get(_RevisionID);
        }
        public static void Refresh(Revision tmp)
        {
            string key = tmp.RevisionID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (RevisionInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(Revision tmp)
        {
            _ItemID = tmp.ItemID;
            _TypeID = tmp.TypeID;
            _RevisionNumber = tmp.RevisionNumber;
            _RevisionDate = tmp.RevisionDate;
            _Notes = tmp.Notes;
            _Config = tmp.Config;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _RevisionInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static RevisionInfo Get(int revisionID)
        {
            //if (!CanGetObject())
            //  throw new System.Security.SecurityException("User not authorized to view a Revision");
            try
            {
                RevisionInfo tmp = GetCachedByPrimaryKey(revisionID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(revisionID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up RevisionInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on RevisionInfo.Get", ex);
            }
        }
        #endregion
        #region Data Access Portal
        internal RevisionInfo(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RevisionInfo.Constructor", GetHashCode());
            try
            {
                ReadData(dr);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("RevisionInfo.Constructor", ex);
                throw new DbCslaException("RevisionInfo.Constructor", ex);
            }
        }
        [Serializable()]
        protected class PKCriteria
        {
            private int _RevisionID;
            public int RevisionID
            { get { return _RevisionID; } }
            public PKCriteria(int revisionID)
            {
                _RevisionID = revisionID;
            }
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RevisionInfo.ReadData", GetHashCode());
            try
            {
                _RevisionID = dr.GetInt32("RevisionID");
                _ItemID = dr.GetInt32("ItemID");
                _TypeID = dr.GetInt32("TypeID");
                _RevisionNumber = dr.GetString("RevisionNumber");
                if (!dr.IsDBNull(dr.GetOrdinal("RevisionDate"))) _RevisionDate = dr.GetDateTime("RevisionDate");
                _Notes = dr.GetString("Notes");
                _Config = dr.GetString("Config");
                _DTS = dr.GetDateTime("DTS");
                _UserID = dr.GetString("UserID");
                _RevisionCheckCount = dr.GetInt32("CheckCount");
                _RevisionVersionCount = dr.GetInt32("VersionCount");
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("RevisionInfo.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("RevisionInfo.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RevisionInfo.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 = "getRevision";
                        cm.Parameters.AddWithValue("@RevisionID", criteria.RevisionID);
                        cm.CommandTimeout = Database.DefaultTimeout;
                        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("RevisionInfo.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("RevisionInfo.DataPortal_Fetch", ex);
            }
        }
        #endregion
        // Standard Refresh
        #region extension
        RevisionInfoExtension _RevisionInfoExtension = new RevisionInfoExtension();
        [Serializable()]
        partial class RevisionInfoExtension : extensionBase { }
        [Serializable()]
        class extensionBase
        {
            // Default Refresh
            public virtual void Refresh(RevisionInfo tmp) { }
        }
        #endregion
    } // Class
    #region Converter
    internal class RevisionInfoConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is RevisionInfo)
            {
                // Return the ToString value
                return ((RevisionInfo)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace