// ========================================================================
// 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 AnnotationInfoEvent(object sender);
    /// 
    ///	AnnotationInfo Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(AnnotationInfoConverter))]
    public partial class AnnotationInfo : ReadOnlyBase, IDisposable
    {
        public event AnnotationInfoEvent 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(AnnotationInfo annotationInfo)
        {
            if (!_CacheList.Contains(annotationInfo)) _CacheList.Add(annotationInfo); // In AddToCache
        }
        protected static void RemoveFromCache(AnnotationInfo annotationInfo)
        {
            while (_CacheList.Contains(annotationInfo)) _CacheList.Remove(annotationInfo); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            List remove = new List();
            foreach (AnnotationInfo tmp in _CacheList)
            {
                if (!_CacheByPrimaryKey.ContainsKey(tmp.AnnotationID.ToString()))
                {
                    _CacheByPrimaryKey[tmp.AnnotationID.ToString()] = new List(); // Add new list for PrimaryKey
                }
                _CacheByPrimaryKey[tmp.AnnotationID.ToString()].Add(tmp); // Add to Primary Key list
                remove.Add(tmp);
            }
            foreach (AnnotationInfo tmp in remove)
                RemoveFromCache(tmp);
        }
        internal static void AddList(AnnotationInfoList lst)
        {
            foreach (AnnotationInfo item in lst) AddToCache(item);
        }
        protected static AnnotationInfo GetCachedByPrimaryKey(int annotationID)
        {
            ConvertListToDictionary();
            string key = annotationID.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 Annotation _Editable;
        private IVEHasBrokenRules HasBrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = null;
                if (_Editable != null)
                    hasBrokenRules = _Editable.HasBrokenRules;
                return hasBrokenRules;
            }
        }
        private int _AnnotationID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int AnnotationID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _AnnotationID;
            }
        }
        private int _ItemID;
        public int ItemID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyItem != null) _ItemID = _MyItem.ItemID;
                return _ItemID;
            }
        }
        private ItemInfo _MyItem;
        public ItemInfo MyItem
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyItem == null && _ItemID != 0) _MyItem = ItemInfo.Get(_ItemID);
                return _MyItem;
            }
        }
        private int _TypeID;
        public int TypeID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyAnnotationType != null) _TypeID = _MyAnnotationType.TypeID;
                return _TypeID;
            }
        }
        private AnnotationTypeInfo _MyAnnotationType;
        public AnnotationTypeInfo MyAnnotationType
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyAnnotationType == null && _TypeID != 0) _MyAnnotationType = AnnotationTypeInfo.Get(_TypeID);
                return _MyAnnotationType;
            }
        }
        private string _RtfText = string.Empty;
        public string RtfText
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _RtfText;
            }
        }
        private string _SearchText = string.Empty;
        public string SearchText
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _SearchText;
            }
        }
        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;
            }
        }
        // TODO: Replace base AnnotationInfo.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current AnnotationInfo
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // TODO: Check AnnotationInfo.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 AnnotationInfo
        protected override object GetIdValue()
        {
            return _AnnotationID;
        }
        #endregion
        #region Factory Methods
        private static int _AnnotationInfoUnique = 0;
        private static int AnnotationInfoUnique
        { get { return ++_AnnotationInfoUnique; } }
        private int _MyAnnotationInfoUnique = AnnotationInfoUnique;
        public int MyAnnotationInfoUnique
        { get { return _MyAnnotationInfoUnique; } }
        protected AnnotationInfo()
        {/* require use of factory methods */
            AddToCache(this);
        }
        public void Dispose()
        {
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(AnnotationID.ToString())) return;
            List listAnnotationInfo = _CacheByPrimaryKey[AnnotationID.ToString()]; // Get the list of items
            while (listAnnotationInfo.Contains(this)) listAnnotationInfo.Remove(this); // Remove the item from the list
            if (listAnnotationInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(AnnotationID.ToString()); // remove the list
        }
        public virtual Annotation Get()
        {
            return _Editable = Annotation.Get(_AnnotationID);
        }
        public static void Refresh(Annotation tmp)
        {
            string key = tmp.AnnotationID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (AnnotationInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(Annotation tmp)
        {
            if (_ItemID != tmp.ItemID)
            {
                if (MyItem != null) MyItem.RefreshItemAnnotations(); // Update List for old value
                _ItemID = tmp.ItemID; // Update the value
            }
            _MyItem = null; // Reset list so that the next line gets a new list
            if (MyItem != null) MyItem.RefreshItemAnnotations(); // Update List for new value
            if (_TypeID != tmp.TypeID)
            {
                if (MyAnnotationType != null) MyAnnotationType.RefreshAnnotationTypeAnnotations(); // Update List for old value
                _TypeID = tmp.TypeID; // Update the value
            }
            _MyAnnotationType = null; // Reset list so that the next line gets a new list
            if (MyAnnotationType != null) MyAnnotationType.RefreshAnnotationTypeAnnotations(); // Update List for new value
            _RtfText = tmp.RtfText;
            _SearchText = tmp.SearchText;
            _Config = tmp.Config;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _AnnotationInfoExtension.Refresh(this);
            if (_MyItem != null)
            {
                _MyItem.Dispose();// Dispose related value
                _MyItem = null;// Reset related value
            }
            if (_MyAnnotationType != null)
            {
                _MyAnnotationType.Dispose();// Dispose related value
                _MyAnnotationType = null;// Reset related value
            }
            OnChange();// raise an event
        }
        public static void Refresh(AnnotationTypeAnnotation tmp)
        {
            string key = tmp.AnnotationID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (AnnotationInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(AnnotationTypeAnnotation tmp)
        {
            if (_ItemID != tmp.ItemID)
            {
                if (MyItem != null) MyItem.RefreshItemAnnotations(); // Update List for old value
                _ItemID = tmp.ItemID; // Update the value
            }
            _MyItem = null; // Reset list so that the next line gets a new list
            if (MyItem != null) MyItem.RefreshItemAnnotations(); // Update List for new value
            _RtfText = tmp.RtfText;
            _SearchText = tmp.SearchText;
            _Config = tmp.Config;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _AnnotationInfoExtension.Refresh(this);
            if (_MyItem != null)
            {
                _MyItem.Dispose();// Dispose related value
                _MyItem = null;// Reset related value
            }
            if (_MyAnnotationType != null)
            {
                _MyAnnotationType.Dispose();// Dispose related value
                _MyAnnotationType = null;// Reset related value
            }
            OnChange();// raise an event
        }
        public static void Refresh(ItemAnnotation tmp)
        {
            string key = tmp.AnnotationID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (AnnotationInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(ItemAnnotation tmp)
        {
            if (_TypeID != tmp.TypeID)
            {
                if (MyAnnotationType != null) MyAnnotationType.RefreshAnnotationTypeAnnotations(); // Update List for old value
                _TypeID = tmp.TypeID; // Update the value
            }
            _MyAnnotationType = null; // Reset list so that the next line gets a new list
            if (MyAnnotationType != null) MyAnnotationType.RefreshAnnotationTypeAnnotations(); // Update List for new value
            _RtfText = tmp.RtfText;
            _SearchText = tmp.SearchText;
            _Config = tmp.Config;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _AnnotationInfoExtension.Refresh(this);
            if (_MyItem != null)
            {
                _MyItem.Dispose();// Dispose related value
                _MyItem = null;// Reset related value
            }
            if (_MyAnnotationType != null)
            {
                _MyAnnotationType.Dispose();// Dispose related value
                _MyAnnotationType = null;// Reset related value
            }
            OnChange();// raise an event
        }
        public static AnnotationInfo Get(int annotationID)
        {
            //if (!CanGetObject())
            //  throw new System.Security.SecurityException("User not authorized to view a Annotation");
            try
            {
                AnnotationInfo tmp = GetCachedByPrimaryKey(annotationID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(annotationID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up AnnotationInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on AnnotationInfo.Get", ex);
            }
        }
        #endregion
        #region Data Access Portal
        internal AnnotationInfo(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationInfo.Constructor", GetHashCode());
            try
            {
                ReadData(dr);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationInfo.Constructor", ex);
                throw new DbCslaException("AnnotationInfo.Constructor", ex);
            }
        }
        [Serializable()]
        protected class PKCriteria
        {
            private int _AnnotationID;
            public int AnnotationID
            { get { return _AnnotationID; } }
            public PKCriteria(int annotationID)
            {
                _AnnotationID = annotationID;
            }
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationInfo.ReadData", GetHashCode());
            try
            {
                _AnnotationID = dr.GetInt32("AnnotationID");
                _ItemID = dr.GetInt32("ItemID");
                _TypeID = dr.GetInt32("TypeID");
                _RtfText = dr.GetString("RtfText");
                _SearchText = dr.GetString("SearchText");
                _Config = dr.GetString("Config");
                _DTS = dr.GetDateTime("DTS");
                _UserID = dr.GetString("UserID");
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationInfo.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("AnnotationInfo.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationInfo.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 = "getAnnotation";
                        cm.Parameters.AddWithValue("@AnnotationID", criteria.AnnotationID);
                        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("AnnotationInfo.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("AnnotationInfo.DataPortal_Fetch", ex);
            }
        }
        #endregion
        // Standard Refresh
        #region extension
        AnnotationInfoExtension _AnnotationInfoExtension = new AnnotationInfoExtension();
        [Serializable()]
        partial class AnnotationInfoExtension : extensionBase { }
        [Serializable()]
        class extensionBase
        {
            // Default Refresh
            public virtual void Refresh(AnnotationInfo tmp) { }
        }
        #endregion
    } // Class
    #region Converter
    internal class AnnotationInfoConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is AnnotationInfo)
            {
                // Return the ToString value
                return ((AnnotationInfo)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace