// ========================================================================
// 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 TransitionInfoEvent(object sender);
    /// 
    ///	TransitionInfo Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(TransitionInfoConverter))]
    public partial class TransitionInfo : ReadOnlyBase, IDisposable
    {
        public event TransitionInfoEvent 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(TransitionInfo transitionInfo)
        {
            if (!_CacheList.Contains(transitionInfo)) _CacheList.Add(transitionInfo); // In AddToCache
        }
        protected static void RemoveFromCache(TransitionInfo transitionInfo)
        {
            while (_CacheList.Contains(transitionInfo)) _CacheList.Remove(transitionInfo); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            while (_CacheList.Count > 0) // Move TransitionInfo(s) from temporary _CacheList to _CacheByPrimaryKey
            {
                TransitionInfo tmp = _CacheList[0]; // Get the first TransitionInfo
                string pKey = tmp.TransitionID.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 TransitionInfo
            }
        }
        internal static void AddList(TransitionInfoList lst)
        {
            foreach (TransitionInfo item in lst) AddToCache(item);
        }
        protected static TransitionInfo GetCachedByPrimaryKey(int transitionID)
        {
            ConvertListToDictionary();
            string key = transitionID.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 Transition _Editable;
        private IVEHasBrokenRules HasBrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = null;
                if (_Editable != null)
                    hasBrokenRules = _Editable.HasBrokenRules;
                return hasBrokenRules;
            }
        }
        private int _TransitionID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int TransitionID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _TransitionID;
            }
        }
        private int _FromID;
        public int FromID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyContent != null) _FromID = _MyContent.ContentID;
                return _FromID;
            }
        }
        private ContentInfo _MyContent;
        public ContentInfo MyContent
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyContent == null && _FromID != 0) _MyContent = ContentInfo.Get(_FromID);
                return _MyContent;
            }
        }
        private int _ToID;
        /// 
        /// StructureID
        /// 
        public int ToID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyItemToID != null) _ToID = _MyItemToID.ItemID;
                return _ToID;
            }
        }
        private ItemInfo _MyItemToID;
        public ItemInfo MyItemToID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyItemToID == null && _ToID != 0) _MyItemToID = ItemInfo.Get(_ToID);
                return _MyItemToID;
            }
        }
        private int _RangeID;
        public int RangeID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyItemRangeID != null) _RangeID = _MyItemRangeID.ItemID;
                return _RangeID;
            }
        }
        private ItemInfo _MyItemRangeID;
        public ItemInfo MyItemRangeID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyItemRangeID == null && _RangeID != 0) _MyItemRangeID = ItemInfo.Get(_RangeID);
                return _MyItemRangeID;
            }
        }
        private int _IsRange;
        /// 
        /// 0 - Not a Range Transition, 1 - Range Transition, 2 - Range Transition - Extends to last Sibling
        /// 
        public int IsRange
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _IsRange;
            }
        }
        private int _TranType;
        public int TranType
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _TranType;
            }
        }
        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 _TransitionZTransitionCount = 0;
        /// 
        /// Count of TransitionZTransitions for this Transition
        /// 
        public int TransitionZTransitionCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _TransitionZTransitionCount;
            }
        }
        private ZTransitionInfo _MyZTransition = null;
        [TypeConverter(typeof(ZTransitionInfoConverter))]
        public ZTransitionInfo MyZTransition
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_TransitionZTransitionCount != 0 && _MyZTransition == null)
                {
                    _MyZTransition = ZTransitionInfo.Get(_TransitionID);
                    _TransitionZTransitionCount = _MyZTransition == null ? 0 : 1;
                }
                return _MyZTransition;
            }
        }
        // CSLATODO: Replace base TransitionInfo.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current TransitionInfo
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // CSLATODO: Check TransitionInfo.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 TransitionInfo
        protected override object GetIdValue()
        {
            return MyTransitionInfoUnique; // Absolutely Unique ID
        }
        #endregion
        #region Factory Methods
        private static int _TransitionInfoUnique = 0;
        private static int TransitionInfoUnique
        { get { return ++_TransitionInfoUnique; } }
        private int _MyTransitionInfoUnique = TransitionInfoUnique;
        public int MyTransitionInfoUnique // Absolutely Unique ID - Info
        { get { return _MyTransitionInfoUnique; } }
        protected TransitionInfo()
        {/* 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; } }
        ~TransitionInfo()
        {
            _CountFinalized++;
        }
        public void Dispose()
        {
            if (_Disposed) return;
            _CountDisposed++;
            _Disposed = true;
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(TransitionID.ToString())) return;
            List listTransitionInfo = _CacheByPrimaryKey[TransitionID.ToString()]; // Get the list of items
            while (listTransitionInfo.Contains(this)) listTransitionInfo.Remove(this); // Remove the item from the list
            if (listTransitionInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(TransitionID.ToString()); // remove the list
        }
        public virtual Transition Get()
        {
            return _Editable = Transition.Get(_TransitionID);
        }
        public static void Refresh(Transition tmp)
        {
            string key = tmp.TransitionID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (TransitionInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(Transition tmp)
        {
            if (_FromID != tmp.FromID)
            {
                if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for old value
                _FromID = tmp.FromID; // Update the value
            }
            _MyContent = null; // Reset list so that the next line gets a new list
            if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for new value
            if (_ToID != tmp.ToID)
            {
                if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for old value
                _ToID = tmp.ToID; // Update the value
            }
            _MyItemToID = null; // Reset list so that the next line gets a new list
            if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for new value
            if (_RangeID != tmp.RangeID)
            {
                if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for old value
                _RangeID = tmp.RangeID; // Update the value
            }
            _MyItemRangeID = null; // Reset list so that the next line gets a new list
            if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for new value
            _IsRange = tmp.IsRange;
            _TranType = tmp.TranType;
            _Config = tmp.Config;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _TransitionInfoExtension.Refresh(this);
            _TransitionZTransitionCount = -1;// Reset Count
            OnChange();// raise an event
        }
        public static void Refresh(ContentTransition tmp)
        {
            string key = tmp.TransitionID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (TransitionInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(ContentTransition tmp)
        {
            if (_ToID != tmp.ToID)
            {
                if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for old value
                _ToID = tmp.ToID; // Update the value
            }
            _MyItemToID = null; // Reset list so that the next line gets a new list
            if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for new value
            if (_RangeID != tmp.RangeID)
            {
                if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for old value
                _RangeID = tmp.RangeID; // Update the value
            }
            _MyItemRangeID = null; // Reset list so that the next line gets a new list
            if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for new value
            _IsRange = tmp.IsRange;
            _TranType = tmp.TranType;
            _Config = tmp.Config;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _TransitionInfoExtension.Refresh(this);
            _TransitionZTransitionCount = -1;// Reset Count
            OnChange();// raise an event
        }
        public static void Refresh(ItemTransition_RangeID tmp)
        {
            string key = tmp.TransitionID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (TransitionInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(ItemTransition_RangeID tmp)
        {
            if (_FromID != tmp.FromID)
            {
                if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for old value
                _FromID = tmp.FromID; // Update the value
            }
            _MyContent = null; // Reset list so that the next line gets a new list
            if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for new value
            if (_ToID != tmp.ToID)
            {
                if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for old value
                _ToID = tmp.ToID; // Update the value
            }
            _MyItemToID = null; // Reset list so that the next line gets a new list
            if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for new value
            _IsRange = tmp.IsRange;
            _TranType = tmp.TranType;
            _Config = tmp.Config;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _TransitionInfoExtension.Refresh(this);
            _TransitionZTransitionCount = -1;// Reset Count
            OnChange();// raise an event
        }
        public static void Refresh(ItemTransition_ToID tmp)
        {
            string key = tmp.TransitionID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (TransitionInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(ItemTransition_ToID tmp)
        {
            if (_FromID != tmp.FromID)
            {
                if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for old value
                _FromID = tmp.FromID; // Update the value
            }
            _MyContent = null; // Reset list so that the next line gets a new list
            if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for new value
            if (_RangeID != tmp.RangeID)
            {
                if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for old value
                _RangeID = tmp.RangeID; // Update the value
            }
            _MyItemRangeID = null; // Reset list so that the next line gets a new list
            if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for new value
            _IsRange = tmp.IsRange;
            _TranType = tmp.TranType;
            _Config = tmp.Config;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _TransitionInfoExtension.Refresh(this);
            _TransitionZTransitionCount = -1;// Reset Count
            OnChange();// raise an event
        }
        public static TransitionInfo Get(int transitionID)
        {
            //if (!CanGetObject())
            //  throw new System.Security.SecurityException("User not authorized to view a Transition");
            try
            {
                TransitionInfo tmp = GetCachedByPrimaryKey(transitionID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(transitionID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up TransitionInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on TransitionInfo.Get", ex);
            }
        }
        #endregion
        #region Data Access Portal
        internal TransitionInfo(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfo.Constructor", GetHashCode());
            try
            {
                ReadData(dr);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfo.Constructor", ex);
                throw new DbCslaException("TransitionInfo.Constructor", ex);
            }
        }
        [Serializable()]
        protected class PKCriteria
        {
            private int _TransitionID;
            public int TransitionID
            { get { return _TransitionID; } }
            public PKCriteria(int transitionID)
            {
                _TransitionID = transitionID;
            }
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfo.ReadData", GetHashCode());
            try
            {
                _TransitionID = dr.GetInt32("TransitionID");
                _FromID = dr.GetInt32("FromID");
                _ToID = dr.GetInt32("ToID");
                _RangeID = dr.GetInt32("RangeID");
                _IsRange = dr.GetInt32("IsRange");
                _TranType = dr.GetInt32("TranType");
                _Config = dr.GetString("Config");
                _DTS = dr.GetDateTime("DTS");
                _UserID = dr.GetString("UserID");
                _TransitionZTransitionCount = dr.GetInt32("ZTransitionCount");
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfo.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("TransitionInfo.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfo.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 = "getTransition";
                        cm.Parameters.AddWithValue("@TransitionID", criteria.TransitionID);
                        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("TransitionInfo.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("TransitionInfo.DataPortal_Fetch", ex);
            }
        }
        #endregion
        // Standard Refresh
        #region extension
        TransitionInfoExtension _TransitionInfoExtension = new TransitionInfoExtension();
        [Serializable()]
        partial class TransitionInfoExtension : extensionBase { }
        [Serializable()]
        class extensionBase
        {
            // Default Refresh
            public virtual void Refresh(TransitionInfo tmp) { }
        }
        #endregion
    } // Class
    #region Converter
    internal class TransitionInfoConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is TransitionInfo)
            {
                // Return the ToString value
                return ((TransitionInfo)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace