// ========================================================================
// 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 PdfInfoEvent(object sender);
    /// 
    ///	PdfInfo Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(PdfInfoConverter))]
    public partial class PdfInfo : ReadOnlyBase, IDisposable
    {
        public event PdfInfoEvent 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(PdfInfo pdfInfo)
        {
            if (!_CacheList.Contains(pdfInfo)) _CacheList.Add(pdfInfo); // In AddToCache
        }
        protected static void RemoveFromCache(PdfInfo pdfInfo)
        {
            while (_CacheList.Contains(pdfInfo)) _CacheList.Remove(pdfInfo); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            while (_CacheList.Count > 0) // Move PdfInfo(s) from temporary _CacheList to _CacheByPrimaryKey
            {
                PdfInfo tmp = _CacheList[0]; // Get the first PdfInfo
                string pKey = tmp.DocID.ToString() + "_" + tmp.DebugStatus.ToString() + "_" + tmp.TopRow.ToString() + "_" + tmp.PageLength.ToString() + "_" + tmp.LeftMargin.ToString() + "_" + tmp.PageWidth.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 PdfInfo
            }
        }
        internal static void AddList(PdfInfoList lst)
        {
            foreach (PdfInfo item in lst) AddToCache(item);
        }
        protected static PdfInfo GetCachedByPrimaryKey(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth)
        {
            ConvertListToDictionary();
            string key = docID.ToString() + "_" + debugStatus.ToString() + "_" + topRow.ToString() + "_" + pageLength.ToString() + "_" + leftMargin.ToString() + "_" + pageWidth.ToString();
            if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0];
            return null;
        }
        // B2023-024 PROMS was using old cached PDF data when printing Word sections.
        //           Added this method to clear the PDF print cache for a specified section.
        //           This is called from RemovePDFFromCache() in PDFExt.cs
        protected static void RemoveFromCachedByPrimaryKey(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth)
        {
            ConvertListToDictionary();
            string key = docID.ToString() + "_" + debugStatus.ToString() + "_" + topRow.ToString() + "_" + pageLength.ToString() + "_" + leftMargin.ToString() + "_" + pageWidth.ToString();
            if (_CacheByPrimaryKey.ContainsKey(key))
            {
                _CacheByPrimaryKey.Remove(key);
            }
            return;
        }
        #endregion
        #region Business Methods
        private string _ErrorMessage = string.Empty;
        public string ErrorMessage
        {
            get { return _ErrorMessage; }
        }
        protected Pdf _Editable;
        private IVEHasBrokenRules HasBrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = null;
                if (_Editable != null)
                    hasBrokenRules = _Editable.HasBrokenRules;
                return hasBrokenRules;
            }
        }
        private int _DocID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int DocID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyDocument != null) _DocID = _MyDocument.DocID;
                return _DocID;
            }
        }
        private DocumentInfo _MyDocument;
        [System.ComponentModel.DataObjectField(true, true)]
        public DocumentInfo MyDocument
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyDocument == null && _DocID != 0) _MyDocument = DocumentInfo.Get(_DocID);
                return _MyDocument;
            }
        }
        private int _DebugStatus;
        /// 
        /// > 0 for Debug
        /// 
        [System.ComponentModel.DataObjectField(true, true)]
        public int DebugStatus
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DebugStatus;
            }
        }
        private int _TopRow;
        [System.ComponentModel.DataObjectField(true, true)]
        public int TopRow
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _TopRow;
            }
        }
        private int _PageLength;
        [System.ComponentModel.DataObjectField(true, true)]
        public int PageLength
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _PageLength;
            }
        }
        private int _LeftMargin;
        [System.ComponentModel.DataObjectField(true, true)]
        public int LeftMargin
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _LeftMargin;
            }
        }
        private int _PageWidth;
        [System.ComponentModel.DataObjectField(true, true)]
        public int PageWidth
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _PageWidth;
            }
        }
        private double _PageCount;
        /// 
        /// Count of whole and partial pages
        /// 
        public double PageCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _PageCount;
            }
        }
        private byte[] _DocPdf;
        public byte[] DocPdf
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DocPdf;
            }
        }
        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 PdfInfo.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current PdfInfo
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // CSLATODO: Check PdfInfo.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 PdfInfo
        protected override object GetIdValue()
        {
            return MyPdfInfoUnique; // Absolutely Unique ID
        }
        #endregion
        #region Factory Methods
        private static int _PdfInfoUnique = 0;
        private static int PdfInfoUnique
        { get { return ++_PdfInfoUnique; } }
        private int _MyPdfInfoUnique = PdfInfoUnique;
        public int MyPdfInfoUnique // Absolutely Unique ID - Info
        { get { return _MyPdfInfoUnique; } }
        protected PdfInfo()
        {/* 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; } }
        ~PdfInfo()
        {
            _CountFinalized++;
        }
        public void Dispose()
        {
            if (_Disposed) return;
            _CountDisposed++;
            _Disposed = true;
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(DocID.ToString() + "_" + DebugStatus.ToString() + "_" + TopRow.ToString() + "_" + PageLength.ToString() + "_" + LeftMargin.ToString() + "_" + PageWidth.ToString())) return;
            List listPdfInfo = _CacheByPrimaryKey[DocID.ToString() + "_" + DebugStatus.ToString() + "_" + TopRow.ToString() + "_" + PageLength.ToString() + "_" + LeftMargin.ToString() + "_" + PageWidth.ToString()]; // Get the list of items
            while (listPdfInfo.Contains(this)) listPdfInfo.Remove(this); // Remove the item from the list
            if (listPdfInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(DocID.ToString() + "_" + DebugStatus.ToString() + "_" + TopRow.ToString() + "_" + PageLength.ToString() + "_" + LeftMargin.ToString() + "_" + PageWidth.ToString()); // remove the list
        }
        public virtual Pdf Get()
        {
            return _Editable = Pdf.Get(_DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth);
        }
        public static void Refresh(Pdf tmp)
        {
            string key = tmp.DocID.ToString() + "_" + tmp.DebugStatus.ToString() + "_" + tmp.TopRow.ToString() + "_" + tmp.PageLength.ToString() + "_" + tmp.LeftMargin.ToString() + "_" + tmp.PageWidth.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (PdfInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(Pdf tmp)
        {
            _PageCount = tmp.PageCount;
            _DocPdf = tmp.DocPdf;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _PdfInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static void Refresh(Document myDocument, DocumentPdf tmp)
        {
            string key = myDocument.DocID.ToString() + "_" + tmp.DebugStatus.ToString() + "_" + tmp.TopRow.ToString() + "_" + tmp.PageLength.ToString() + "_" + tmp.LeftMargin.ToString() + "_" + tmp.PageWidth.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (PdfInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(DocumentPdf tmp)
        {
            _PageCount = tmp.PageCount;
            _DocPdf = tmp.DocPdf;
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _PdfInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static PdfInfo Get(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth)
        {
            //if (!CanGetObject())
            //  throw new System.Security.SecurityException("User not authorized to view a Pdf");
            try
            {
                PdfInfo tmp = GetCachedByPrimaryKey(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth));
                    if (tmp.DocID > 0) AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up PdfInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on PdfInfo.Get", ex);
            }
        }
        #endregion
        #region Data Access Portal
        internal PdfInfo(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PdfInfo.Constructor", GetHashCode());
            try
            {
                ReadData(dr);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("PdfInfo.Constructor", ex);
                throw new DbCslaException("PdfInfo.Constructor", ex);
            }
        }
        [Serializable()]
        protected class PKCriteria
        {
            private int _DocID;
            public int DocID
            { get { return _DocID; } }
            private int _DebugStatus;
            public int DebugStatus
            { get { return _DebugStatus; } }
            private int _TopRow;
            public int TopRow
            { get { return _TopRow; } }
            private int _PageLength;
            public int PageLength
            { get { return _PageLength; } }
            private int _LeftMargin;
            public int LeftMargin
            { get { return _LeftMargin; } }
            private int _PageWidth;
            public int PageWidth
            { get { return _PageWidth; } }
            public PKCriteria(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth)
            {
                _DocID = docID;
                _DebugStatus = debugStatus;
                _TopRow = topRow;
                _PageLength = pageLength;
                _LeftMargin = leftMargin;
                _PageWidth = pageWidth;
            }
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PdfInfo.ReadData", GetHashCode());
            try
            {
                _DocID = dr.GetInt32("DocID");
                _DebugStatus = dr.GetInt32("DebugStatus");
                _TopRow = dr.GetInt32("TopRow");
                _PageLength = dr.GetInt32("PageLength");
                _LeftMargin = dr.GetInt32("LeftMargin");
                _PageWidth = dr.GetInt32("PageWidth");
                _PageCount = dr.GetDouble("PageCount");
                _DocPdf = (byte[])dr.GetValue("DocPdf");
                _DTS = dr.GetDateTime("DTS");
                _UserID = dr.GetString("UserID");
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("PdfInfo.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("PdfInfo.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PdfInfo.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 = "getPdf";
                        cm.Parameters.AddWithValue("@DocID", criteria.DocID);
                        cm.Parameters.AddWithValue("@DebugStatus", criteria.DebugStatus);
                        cm.Parameters.AddWithValue("@TopRow", criteria.TopRow);
                        cm.Parameters.AddWithValue("@PageLength", criteria.PageLength);
                        cm.Parameters.AddWithValue("@LeftMargin", criteria.LeftMargin);
                        cm.Parameters.AddWithValue("@PageWidth", criteria.PageWidth);
                        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("PdfInfo.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("PdfInfo.DataPortal_Fetch", ex);
            }
        }
        #endregion
        // Standard Refresh
        #region extension
        PdfInfoExtension _PdfInfoExtension = new PdfInfoExtension();
        [Serializable()]
        partial class PdfInfoExtension : extensionBase { }
        [Serializable()]
        class extensionBase
        {
            // Default Refresh
            public virtual void Refresh(PdfInfo tmp) { }
        }
        #endregion
    } // Class
    #region Converter
    internal class PdfInfoConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is PdfInfo)
            {
                // Return the ToString value
                return ((PdfInfo)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace