// ========================================================================
// 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;
using System.Linq;
namespace VEPROMS.CSLA.Library
{
    public delegate void GridInfoEvent(object sender);
    /// 
    ///	GridInfo Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(GridInfoConverter))]
    public partial class GridInfo : ReadOnlyBase, IDisposable
    {
        public event GridInfoEvent 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(GridInfo gridInfo)
        {
            if (!_CacheList.Contains(gridInfo)) _CacheList.Add(gridInfo); // In AddToCache
        }
        protected static void RemoveFromCache(GridInfo gridInfo)
        {
            while (_CacheList.Contains(gridInfo)) _CacheList.Remove(gridInfo); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            while (_CacheList.Count > 0) // Move GridInfo(s) from temporary _CacheList to _CacheByPrimaryKey
            {
                GridInfo tmp = _CacheList[0]; // Get the first GridInfo
                string pKey = tmp.ContentID.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 GridInfo
            }
        }
        protected static GridInfo GetCachedByPrimaryKey(int contentID)
        {
            ConvertListToDictionary();
            string key = contentID.ToString();
            if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0];
            return null;
        }
        public static void ClearGridInfoCache()
        {
            while (_CacheByPrimaryKey.Count > 0)
            {
                var ii = _CacheByPrimaryKey.FirstOrDefault();
                while (ii.Value.Count > 0)
                {
                    if (ii.Value[0]?.MyContent?.ContentParts != null)
                    { foreach (PartInfo pi in ii.Value[0]?.MyContent?.ContentParts) pi.Dispose(); }
                    ii.Value[0].Dispose();
                }
                _CacheByPrimaryKey.Remove(ii.Key);
            }
            while (_CacheList.Count > 0)
            {
                _CacheList[0].Dispose();
            }
        }
        #endregion
        #region Business Methods
        private string _ErrorMessage = string.Empty;
        public string ErrorMessage
        {
            get { return _ErrorMessage; }
        }
        protected Grid _Editable;
        private IVEHasBrokenRules HasBrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = null;
                if (_Editable != null)
                    hasBrokenRules = _Editable.HasBrokenRules;
                return hasBrokenRules;
            }
        }
        private int _ContentID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int ContentID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyContent != null) _ContentID = _MyContent.ContentID;
                return _ContentID;
            }
        }
        private ContentInfo _MyContent;
        [System.ComponentModel.DataObjectField(true, true)]
        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 string _Data = string.Empty;
        public string Data
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _Data;
            }
        }
        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;
            }
        }
        // CSLATODO: Replace base GridInfo.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current GridInfo
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // CSLATODO: Check GridInfo.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 GridInfo
        protected override object GetIdValue()
        {
            return MyGridInfoUnique; // Absolutely Unique ID
        }
        #endregion
        #region Factory Methods
        private static int _GridInfoUnique = 0;
        private static int GridInfoUnique
        { get { return ++_GridInfoUnique; } }
        private int _MyGridInfoUnique = GridInfoUnique;
        public int MyGridInfoUnique // Absolutely Unique ID - Info
        { get { return _MyGridInfoUnique; } }
        protected GridInfo()
        {/* 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; } }
        ~GridInfo()
        {
            _CountFinalized++;
        }
        public void Dispose()
        {
            if (_Disposed) return;
            _CountDisposed++;
            _Disposed = true;
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(ContentID.ToString())) return;
            List listGridInfo = _CacheByPrimaryKey[ContentID.ToString()]; // Get the list of items
            while (listGridInfo.Contains(this)) listGridInfo.Remove(this); // Remove the item from the list
            if (listGridInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list
        }
        public virtual Grid Get()
        {
            return _Editable = Grid.Get(_ContentID);
        }
        public static void Refresh(Grid tmp)
        {
            string key = tmp.ContentID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (GridInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(Grid tmp)
        {
            _Data = tmp.Data;
            _Config = tmp.Config;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _GridInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static GridInfo Get(int contentID)
        {
            //if (!CanGetObject())
            //  throw new System.Security.SecurityException("User not authorized to view a Grid");
            try
            {
                GridInfo tmp = GetCachedByPrimaryKey(contentID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(contentID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up GridInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on GridInfo.Get", ex);
            }
        }
        #endregion
        #region Data Access Portal
        internal GridInfo(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridInfo.Constructor", GetHashCode());
            try
            {
                ReadData(dr);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("GridInfo.Constructor", ex);
                throw new DbCslaException("GridInfo.Constructor", ex);
            }
        }
        [Serializable()]
        protected class PKCriteria
        {
            private int _ContentID;
            public int ContentID
            { get { return _ContentID; } }
            public PKCriteria(int contentID)
            {
                _ContentID = contentID;
            }
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridInfo.ReadData", GetHashCode());
            try
            {
                _ContentID = dr.GetInt32("ContentID");
                _Data = dr.GetString("Data");
                _Config = dr.GetString("Config");
                _DTS = dr.GetDateTime("DTS");
                _UserID = dr.GetString("UserID");
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("GridInfo.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("GridInfo.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridInfo.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 = "getGrid";
                        cm.Parameters.AddWithValue("@ContentID", criteria.ContentID);
                        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("GridInfo.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("GridInfo.DataPortal_Fetch", ex);
            }
        }
        #endregion
        // Standard Refresh
        #region extension
        GridInfoExtension _GridInfoExtension = new GridInfoExtension();
        [Serializable()]
        partial class GridInfoExtension : extensionBase { }
        [Serializable()]
        class extensionBase
        {
            // Default Refresh
            public virtual void Refresh(GridInfo tmp) { }
        }
        #endregion
    } // Class
    #region Converter
    internal class GridInfoConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is GridInfo)
            {
                // Return the ToString value
                return ((GridInfo)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace