// ========================================================================
// 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
        private static List _CacheList = new List();
        protected static void AddToCache(ItemInfo itemInfo)
        {
            if (!_CacheList.Contains(itemInfo)) _CacheList.Add(itemInfo); // In AddToCache
        }
        protected static void RemoveFromCache(ItemInfo itemInfo)
        {
            while (_CacheList.Contains(itemInfo)) _CacheList.Remove(itemInfo); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            List remove = new List();
            foreach (ItemInfo tmp in _CacheList)
            {
                if (!_CacheByPrimaryKey.ContainsKey(tmp.ItemID.ToString()))
                {
                    _CacheByPrimaryKey[tmp.ItemID.ToString()] = new List(); // Add new list for PrimaryKey
                }
                _CacheByPrimaryKey[tmp.ItemID.ToString()].Add(tmp); // Add to Primary Key list
                remove.Add(tmp);
            }
            foreach (ItemInfo tmp in remove)
                RemoveFromCache(tmp);
        }
        internal static void AddList(ItemInfoList lst)
        {
            foreach (ItemInfo item in lst) AddToCache(item);
        }
        protected static ItemInfo GetCachedByPrimaryKey(int itemID)
        {
            ConvertListToDictionary();
            string key = itemID.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 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
            {
                return _ItemID;
            }
        }
        private int? _PreviousID;
        public int? PreviousID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyPrevious != null) _PreviousID = _MyPrevious.ItemID;
                return _PreviousID;
            }
        }
        private ItemInfo _MyPrevious;
        public ItemInfo MyPrevious
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                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
            {
                if (_MyContent != null) _ContentID = _MyContent.ContentID;
                return _ContentID;
            }
        }
        private ContentInfo _MyContent;
        public ContentInfo MyContent
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                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
            {
                return _DTS;
            }
        }
        private string _UserID = string.Empty;
        public string UserID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                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
            {
                return _ItemAnnotationCount;
            }
        }
        private AnnotationInfoList _ItemAnnotations = null;
        [TypeConverter(typeof(AnnotationInfoListConverter))]
        public AnnotationInfoList ItemAnnotations
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemAnnotationCount < 0 || (_ItemAnnotationCount > 0 && _ItemAnnotations == null))
                    _ItemAnnotations = AnnotationInfoList.GetByItemID(_ItemID);
                if (_ItemAnnotationCount < 0)
                    _ItemAnnotationCount = _ItemAnnotations.Count;
                return _ItemAnnotations;
            }
        }
        public void RefreshItemAnnotations()
        {
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemAnnotationCount = -1; // This will cause the data to be requeried
        }
        private int _ItemDocVersionCount = 0;
        /// 
        /// Count of ItemDocVersions for this Item
        /// 
        public int ItemDocVersionCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ItemDocVersionCount;
            }
        }
        private DocVersionInfoList _ItemDocVersions = null;
        [TypeConverter(typeof(DocVersionInfoListConverter))]
        public DocVersionInfoList ItemDocVersions
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemDocVersionCount < 0 || (_ItemDocVersionCount > 0 && _ItemDocVersions == null))
                    _ItemDocVersions = DocVersionInfoList.GetByItemID(_ItemID);
                if (_ItemDocVersionCount < 0)
                    _ItemDocVersionCount = _ItemDocVersions.Count;
                return _ItemDocVersions;
            }
        }
        public void RefreshItemDocVersions()
        {
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemDocVersionCount = -1; // This will cause the data to be requeried
        }
        private int _NextItemCount = 0;
        /// 
        /// Count of NextItems for this Item
        /// 
        public int NextItemCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _NextItemCount;
            }
        }
        private ItemInfoList _NextItems = null;
        [TypeConverter(typeof(ItemInfoListConverter))]
        public ItemInfoList NextItems
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_NextItemCount < 0 || (_NextItemCount > 0 && _NextItems == null))
                    _NextItems = ItemInfoList.GetNext(_ItemID);
                if (_NextItemCount < 0)
                    _NextItemCount = _NextItems.Count;
                return _NextItems;
            }
        }
        public void RefreshNextItems()
        {
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._NextItemCount = -1; // This will cause the data to be requeried
        }
        private int _ItemPartCount = 0;
        /// 
        /// Count of ItemParts for this Item
        /// 
        public int ItemPartCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ItemPartCount;
            }
        }
        private PartInfoList _ItemParts = null;
        [TypeConverter(typeof(PartInfoListConverter))]
        public PartInfoList ItemParts
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemPartCount < 0 || (_ItemPartCount > 0 && _ItemParts == null))
                    _ItemParts = PartInfoList.GetByItemID(_ItemID);
                if (_ItemPartCount < 0)
                    _ItemPartCount = _ItemParts.Count;
                return _ItemParts;
            }
        }
        public void RefreshItemParts()
        {
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemPartCount = -1; // This will cause the data to be requeried
        }
        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
            {
                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
            {
                if (_ItemTransition_RangeIDCount < 0 || (_ItemTransition_RangeIDCount > 0 && _ItemTransitions_RangeID == null))
                    _ItemTransitions_RangeID = TransitionInfoList.GetByRangeID(_ItemID);
                if (_ItemTransition_RangeIDCount < 0)
                    _ItemTransition_RangeIDCount = _ItemTransitions_RangeID.Count;
                return _ItemTransitions_RangeID;
            }
        }
        public void RefreshItemTransitions_RangeID()
        {
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemTransition_RangeIDCount = -1; // This will cause the data to be requeried
        }
        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
            {
                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
            {
                if (_ItemTransition_ToIDCount < 0 || (_ItemTransition_ToIDCount > 0 && _ItemTransitions_ToID == null))
                    _ItemTransitions_ToID = TransitionInfoList.GetByToID(_ItemID);
                if (_ItemTransition_ToIDCount < 0)
                    _ItemTransition_ToIDCount = _ItemTransitions_ToID.Count;
                return _ItemTransitions_ToID;
            }
        }
        public void RefreshItemTransitions_ToID()
        {
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemTransition_ToIDCount = -1; // This will cause the data to be requeried
        }
        // 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 static int _ItemInfoUnique = 0;
        private static int ItemInfoUnique
        { get { return ++_ItemInfoUnique; } }
        private int _MyItemInfoUnique = ItemInfoUnique;
        public int MyItemInfoUnique
        { get { return _MyItemInfoUnique; } }
        protected ItemInfo()
        {/* require use of factory methods */
            AddToCache(this);
        }
        public void Dispose()
        {
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(ItemID.ToString())) return;
            List listItemInfo = _CacheByPrimaryKey[ItemID.ToString()]; // Get the list of items
            while (listItemInfo.Contains(this)) listItemInfo.Remove(this); // Remove the item from the list
            if (listItemInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(ItemID.ToString()); // remove the list
        }
        public virtual Item Get()
        {
            return _Editable = Item.Get(_ItemID);
        }
        public static void Refresh(Item tmp)
        {
            string key = tmp.ItemID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (ItemInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(Item tmp)
        {
            if (_PreviousID != tmp.PreviousID)
            {
                if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for old value
                _PreviousID = tmp.PreviousID; // Update the value
            }
            _MyPrevious = null; // Reset list so that the next line gets a new list
            if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for new value
            if (_ContentID != tmp.ContentID)
            {
                if (MyContent != null) MyContent.RefreshContentItems(); // Update List for old value
                _ContentID = tmp.ContentID; // Update the value
            }
            _MyContent = null; // Reset list so that the next line gets a new list
            if (MyContent != null) MyContent.RefreshContentItems(); // Update List for new value
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _ItemInfoExtension.Refresh(this);
            if (_MyPrevious != null)
            {
                _MyPrevious.Dispose();// Dispose related value
                _MyPrevious = null;// Reset related value
            }
            if (_MyContent != null)
            {
                _MyContent.Dispose();// Dispose related value
                _MyContent = null;// Reset related value
            }
            OnChange();// raise an event
        }
        public static void Refresh(ContentItem tmp)
        {
            string key = tmp.ItemID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (ItemInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(ContentItem tmp)
        {
            if (_PreviousID != tmp.PreviousID)
            {
                if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for old value
                _PreviousID = tmp.PreviousID; // Update the value
            }
            _MyPrevious = null; // Reset list so that the next line gets a new list
            if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for new value
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _ItemInfoExtension.Refresh(this);
            if (_MyPrevious != null)
            {
                _MyPrevious.Dispose();// Dispose related value
                _MyPrevious = null;// Reset related value
            }
            if (_MyContent != null)
            {
                _MyContent.Dispose();// Dispose related value
                _MyContent = null;// Reset related value
            }
            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 = GetCachedByPrimaryKey(itemID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(itemID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up ItemInfo
                    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