Imports System.Web.HttpContext
Imports System.Web
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.CommonEntities.Library.Enumerations
Imports CharterDotCom.CommonEntities.Library.EntityMemberServices
Imports CharterDotCom.CommonEntities.Library.EntityEBSServices
Imports CharterDotCom.CommonEntities.Library.EntitySupport
Imports CharterDotCom.CommonEntities.Library.EntitySearch
Imports CharterDotCom.CommonEntities.Library.EntityWebConfig
Imports CharterDotCom.CommonEntities.Library.EntityG2BServices
Imports System.Configuration
Imports System.Runtime.Remoting
Imports System.Web.Caching
Imports CharterDotCom.WebSite.Library
Imports System.IO


Public Class ContentManager

    Private _trackingID As String
    'Private _com As ContentClient
    Private _com As BLContentManager

    Public Shared currentContext As HttpContext = HttpContext.Current

    Private Sub New()
        Dim cmSession As Object = HttpContext.Current.Session(BLCommon.ContentManagerKey)
    If Not cmSession Is Nothing Then
      _com = New BLContentManager(DirectCast(cmSession, Dictionary(Of String, Object)))
    Else
      _com = New BLContentManager
    End If

        _trackingID = HttpContext.Current.Session.SessionID



        'Try

        '    Common.RegisterChannels()
        '    ContentManagerProxy = CType(Activator.GetObject(GetType(ContentClient), CStr(HttpContext.Current.Application("RemoteURL_ContentManager"))), ContentClient)
        '    If Not HttpContext.Current.Request.Cookies(CookieName.SessionID) Is Nothing Then
        '        _trackingID = ContentManagerProxy.Initialize(HttpContext.Current.Request.Cookies(CookieName.SessionID).Value)
        '    Else
        '        _trackingID = ContentManagerProxy.Initialize(Nothing)
        '        HttpContext.Current.Response.Cookies.Add(New HttpCookie(CookieName.SessionID, TrackingID))
        '    End If
        'Catch ex As Exception
        '    Throw ex
        'End Try
    End Sub

    Public Sub Destory()
        Try
            ContentManagerProxy.Destroy(TrackingID)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Friend ReadOnly Property TrackingID() As String
        Get
            Return _trackingID
        End Get
    End Property

    Friend Property ContentManagerProxy() As BLContentManager
        Get
            Return _com
        End Get
        Set(ByVal value As BLContentManager)
            _com = value
        End Set
    End Property

    ' returns an instance of Account Manager
    Public Shared Function Instance() As ContentManager
        Try
            'If Common.RetriveFromSession(Common.ContentManagerKey) Is Nothing Then
            '  'If user instance does not exist, create one
            '  Common.AddToSession((Common.ContentManagerKey), New ContentManager())
            '  Return CType(Common.RetriveFromSession(Common.ContentManagerKey), ContentManager)
            'Else
            '  'If user instance already exists, return that
            '  Return CType(Common.RetriveFromSession(Common.ContentManagerKey), ContentManager)
            'End If
            Return New ContentManager
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function GetTemplateHeaderInfo(ByVal templateId As Int32) As Xml.XmlNode
        Dim info As Object = HttpContext.Current.Application("templateHeaderInfo")
        If info Is Nothing Then
            Dim manager As BLContentManager = New BLContentManager()
            manager.LoadTemplateHeaderInfo()
            info = HttpContext.Current.Application("templateHeaderInfo")
        End If

        Dim _headerInfo As Xml.XmlNode = CType(info, Xml.XmlNode)
        Return _headerInfo("Template" & templateId)
    End Function


#Region "Version Maintenance Functions"

    Public Function GetContentID(ByVal UserControl As String, ByVal OwnerID As String, ByVal Ownertype As OwnerType) As Integer
        Try
            Return ContentManagerProxy.GetContentID(TrackingID, UserControl, OwnerID, Ownertype.ToString)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function GetVersions(ByVal ContentID As Integer) As List(Of ContentSchema.VERSION)
        Try
            Return ContentManagerProxy.GetVersions(TrackingID, ContentID)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Sub UpdateVersionText(ByVal VersionId As Integer, ByVal VersionText As String, ByVal VersionName As String, ByVal SearchResultDisplayable As Boolean)
        Try
            ContentManagerProxy.UpdateVersionText(TrackingID, VersionId, VersionText, VersionName, SearchResultDisplayable)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub DeleteVersion(ByVal versionID As Integer)
        Try
            ContentManagerProxy.DeleteVersion(TrackingID, versionID)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Function AddVersion(ByVal ContentID As Integer, ByVal VersionName As String, ByVal VersionText As String) As Boolean
        Try
            Return ContentManagerProxy.AddVersion(TrackingID, ContentID, VersionName, VersionText)
        Catch ex As Exception
            Throw ex

        End Try
    End Function

    Public Function GetCharterMessages(ByVal UserControl As String) As List(Of String)
        Try
            Return ContentManagerProxy.GetCharterMessages(TrackingID, UserControl)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

#End Region

#Region "Schedule Maintenance Functions"

    Public Function GetSchedules(ByVal VersionID As Integer) As List(Of ContentSchema.SCHEDULE)
        Try
            Return ContentManagerProxy.GetSchedules(TrackingID, VersionID)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Sub UpdateSchedule(ByVal ScheduleID As Integer, ByVal Startdate As Date, ByVal EndDate As Date)
        Try
            ContentManagerProxy.UpdateSchedule(TrackingID, ScheduleID, Startdate, EndDate)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub AddSchedule(ByVal VersionID As Integer, ByVal Startdate As Date, ByVal EndDate As Date)
        Try
            ContentManagerProxy.AddSchedule(TrackingID, VersionID, Startdate, EndDate)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub DeleteSchedule(ByVal ScheduleID As Integer)
        Try
            ContentManagerProxy.DeleteSchedule(TrackingID, ScheduleID)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region

#Region "Version Image Maintenance Functions"

    Public Function GetImageForVersion(ByVal VersionID As Integer) As ContentSchema.IMAGE()
        Try
            Return ContentManagerProxy.GetImageForVersion(TrackingID, VersionID)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Sub UpdateVersionImage(ByVal objVersion As ContentSchema.IMAGE)
        Try
            ContentManagerProxy.UpdateVersionImage(TrackingID, objVersion)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub DeleteVersionImage(ByVal ImageID As Integer, ByVal versionID As Integer)
        Try
            ContentManagerProxy.DeleteVersionImage(TrackingID, ImageID, versionID)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub AddVersionImage(ByVal objImage As ContentSchema.IMAGE)
        Try
            ContentManagerProxy.AddVersionImage(TrackingID, objImage)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region

#Region "Image Maintenance Functions"

    Public Function GetImages() As List(Of String)
        Try
            Return ContentManagerProxy.GetImages(TrackingID)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function AddImage(ByVal Name As String, ByVal ImageData() As Byte) As Boolean
        Try
            Return ContentManagerProxy.AddImage(TrackingID, Name, ImageData)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Sub DeleteImage(ByVal Name As String)
        Try
            ContentManagerProxy.DeleteImage(TrackingID, Name)
        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Public Function GetImage(ByVal ImageName As String) As ContentSchema.IMAGE
        Try
            Return ContentManagerProxy.GetImage(TrackingID, ImageName)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

#End Region

#Region "Product catalog Content display Functions"
    Public Function GetContent(ByVal UserControl As String, ByVal OwnerID As String, ByVal Ownertype As OwnerType) As String

        ' THE FUNCTION GETS THE CONTENT FOR THE USERCONTROL SUPPLIED.  THE FIRST TIME IT IS CALLED AND NO CACHE EXISTS
        ' FOR THE GIVEN CONTROL, THEN IT WILL GET THE CONTENT FROM THE DATABASE. AFTER THAT ANY SUBSEQUENT CALLS WILL BE FETCHED
        ' FROM THE CACHE PROVIDED THAT IT STILL EXISTS THERE OR A CACHE REST HAS NOT BEEN APPLIED.
        ' 
        Try
            Dim strTemp As String
            Dim dependencies As String() = {"OutputCacheDependencyKey"}
            'Reference to the current context
            Dim context As HttpContext = HttpContext.Current
            Dim cacheentry As Object = context.Application(context.Request.Url.LocalPath)

            If Not cacheentry Is Nothing Then
                dependencies(0) = CStr(cacheentry)
            End If

            '-----------------------------------------------------------------------------------------------------
            ' ISSUE #nnnnn  05-27-2011  JLN
            '-----------------------------------------------------------------------------------------------------
            ' Description:  Allow for configuration control of Synchronoss and non-Synchronoss content.  This
            '               gives us the ability to have side-by-side content records with different navigation
            '               links.  The configuration flag determines which to use.  This is necessary to get
            '               the site ready for a possible shut-down of the Synchronoss site.
            '      Change:  Added the specified configuration value to the WebConfig database table.  Then,
            '               if Synchronoss content is not enabled, strip the :SYCH from the content key value,
            '               if necessary, and use the resulting key instead.
            '-----------------------------------------------------------------------------------------------------
            Dim contentEnabled As Object = context.Application("SYNCHRONOSS_PROJECT_CONTENT_ENABLED")
            If contentEnabled IsNot Nothing Then
                If contentEnabled.ToString.Trim.ToUpper <> "T" Then
                    If UserControl.Trim.ToUpper.EndsWith(":SYCH") Then
                        UserControl = UserControl.Substring(0, UserControl.Length - 5)
                    End If
                End If
            End If
            '-----------------------------------------------------------------------------------------------------

            If context.Cache("*CMSVersion*" & UserControl & OwnerID & Ownertype.ToString) Is Nothing Then
                'For debug info
                'SaveTextToFile("CREATE Cache --> " & UserControl, "C:\CHARTERDOTCOM\Cache.txt", "")
                strTemp = ContentManagerProxy.GetContent(TrackingID, UserControl, OwnerID, Ownertype.ToString)
                If strTemp Is Nothing Then strTemp = ""


                '#############################################################################
                'MODIFICATION   MAR 6, 2009     ROD COPELAND
                '#############################################################################
                'NORMAL OPERATION: DUMP/EXPIRE CACHE AT 3AM TODAY UNLESS IT'S AFTER 3AM, THEN JUST 
                'DUMP/EXPIRE CACHE 3AM TOMORROW MORNING.
                '#############################################################################
                'THE CONTENT CACHE IS ABLE TO BE DUMPED BASED ON AN ADMIN USER MANUALLY 
                'CLICKING THE RESET CACHE BUTTON IN THE ADMIN UI ON THE APP TIER.  THERE IS 
                'ANOTHER NOT SO WE'LL KNOWN FEATURE OF THE SITE THAT DUMPS THE CACHE 
                'AUTOMATICALLY AT 3AM BY SETTING THE CONTENT EXPIRATION DATE WHEN ADDING TO THE 
                'HTTP CACHE COLLECTION. THE EXPIRATION DATE OF THE CONTENT IS INTENDED TO BE A 
                'CONFIGURABLE VALUE TO BE CHANGED AT RUNTIME FOR NEW ENTRIES TO THE CACHE ONLY.  
                'THIS VALUE SHOULD EXIST IN THE ADMIN.WEBCONFIG TABLE WITH A KEY OF 
                '"NUM_OF_DAYS_TO_CACHE" AND "NUM_OF_HOURS_TO_CACHE".  DETAILS OF THE USE OF 
                'THESE VALUES CAN BE FOUND IN THE 
                'commonEntities.Library.dll\virtualManagers\GenericClient.vb\GenerateContentCacheExpirationDate() 
                'method  ANY EXCEPTION IN THE FUNCTION CALL TO GET THE 
                'EXPIRATION DATE WILL SHOULD RESULT IN A RETURNED DATE OF 2 DAYS FROM NOW AT 3AM.
                '#############################################################################
                Dim lManager As New BLContentManager
                Dim expiredate As DateTime = lManager.GenerateContentCacheExpirationDate()
                '#############################################################################





                '###########################################################################
                'ROD COPELAND   FEB 9, 2009     CREATIVE LIFT REDESIGN PROJECT
                '###########################################################################
                'WHEN ADDING ITEMS TO CACHE, A PRIORITY IS ASSIGNED TO THE ITEM. IN TIMES 
                'OF LOW RESOURCES ON THE BOX, THE .NET FRAMEWORK STARTS REMOVING ITEMS 
                'WITH LOWEST PRIORITY FIRST TO KEEP THE APPLICATION ALIVE. THE CONCERN IS 
                'IF THE APP IS NOT CACHING, IT'S LIKELY MAKING A REMOTING CALL TO GET THE 
                'DATA.  TO MANY REMOTING CALLS AT THE SAME TIME WILL CAUSE A REMOTING CALL 
                'BOTTLE NECK, AT THAT POINT THE APPLICATION WILL START QUEUEING THE CALLS. 
                'ALL THE QUEUED REMOTING CALLS WILL EVENTUALLY RUN UP THE CPU IF NOT 
                'CLEARED.  IF NOT CLEARED THE BOX WILL STOP RESPONDING.
                '###########################################################################
                'THE FOLLOWING IS THE ORDER OF PRIORITY AT THE TIME THIS WAS WRITTEN:
                'CONTENT RECORDS,       NOT REMOVABLE = 6                                           CONTENTMANAGER.GetContent()
                'CCOM IMAGE FILES,      NOT REMOVABLE = 6                                           CONTENTIMAGEHANDLER.ProcessRequest()
                'XBIN PDF FILES,        THIS ITEM IS NOT CACHED AT THIS TIME DUE TO SIZE REASONS.
                'SUPPORT ARTICLES,      ABOVE NORMAL = 4                                            SITEMANAGER.GETDOCUMENT()
                'CCSWF FLASH FILES,     BELOW NORMAL = 3                                                  CONTENTBINARYFILEHANDLER.ProcessRequest()
                'CCXML FILES,           BELOW NORMAL = 2                                            CONTENTBINARYFILEHANDLER.ProcessRequest()
                'CCFLV FILES,           LOW = 1                                                     CONTENTBINARYFILEHANDLER.ProcessRequest()
                '############################################################################
                context.Cache.Insert("*CMSVersion*" & UserControl & OwnerID & Ownertype.ToString, strTemp, New CacheDependency(Nothing, dependencies), expiredate, System.Web.Caching.Cache.NoSlidingExpiration, Caching.CacheItemPriority.NotRemovable, Nothing)
            Else
                'For debug info
                'SaveTextToFile("READ Cache --> " & UserControl, "C:\CHARTERDOTCOM\Cache.txt", "")  'make sure this file writable by the aspnet process / or everyone
                strTemp = CStr(context.Cache("*CMSVersion*" & UserControl & OwnerID & Ownertype.ToString))
            End If


            Return strTemp
        Catch ex As Exception
            Throw ex
        End Try
    End Function


    'Naqib- this is a func for debug purpose
    Public Function SaveTextToFile(ByVal strData As String, ByVal FullPath As String, Optional ByVal ErrInfo As String = "") As Boolean

        Dim Contents As String
        Dim bAns As Boolean = False
        Dim objStreamWriter As StreamWriter
        Try


            objStreamWriter = File.AppendText(FullPath)            
            objStreamWriter.WriteLine(HttpContext.Current.Request.Url.ToString() & " --> " & strData)
            objStreamWriter.Close()

            bAns = True
        Catch Ex As Exception
            ErrInfo = Ex.Message

        End Try
        Return bAns
    End Function


    'Public Sub RemovedCallback(ByVal key As String, ByVal value As Object, ByVal reason As CacheItemRemovedReason)
    '  Try
    '    If InStr(key, "CMSVersion") > 0 Then
    '      If currentContext.Application("CacheHandled") Is Nothing OrElse CStr(currentContext.Application("CacheHandled")) = "false" Then
    '        currentContext.Application.Lock()
    '        currentContext.Application.Add("CacheHandled", "true")
    '        currentContext.Application.UnLock()
    '        Dim wsConfigProvider As New ConfigProvider.Service
    '        Dim ds As New DataSet
    '        Dim usercontrols As New List(Of String)
    '        wsConfigProvider.Url = ConfigurationManager.AppSettings("ConfigProvider.service")
    '        ds = wsConfigProvider.GetWebConfig(ConfigurationManager.AppSettings("ConfigLocation"))

    '        For Each row As Data.DataRow In ds.Tables(0).Rows
    '          Select Case row.Item("Key").ToString()
    '            Case "UserControl"
    '              If Not usercontrols.Contains(CStr(row.Item("XMLData"))) Then usercontrols.Add(CStr(row.Item("XMLData")))
    '            Case Else
    '              ' do nothing
    '          End Select
    '        Next
    '        currentContext.Application.Lock()
    '        currentContext.Application.Remove("UserControl")
    '        currentContext.Application.Add("UserControl", usercontrols)
    '        currentContext.Application.UnLock()
    '        ds = Nothing
    '        wsConfigProvider = Nothing
    '      End If
    '    End If
    '  Catch ex As Exception
    '    Throw ex
    '  End Try
    'End Sub

  Public Function GetContentByTemplateID(ByVal TemplateID As Integer) As DataTable
    Try
      Return ContentManagerProxy.GetContentByTemplateID(TrackingID, TemplateID)
    Catch ex As Exception
      Throw ex
    End Try
  End Function


#End Region

#Region "Organization structure Functions"
  'This sub-routine is called on changing Organization level 
  Public Sub SetOrganization(ByVal OrganizationID As String)
    Try
      ContentManagerProxy.SetOrganization(TrackingID, OrganizationID)
    Catch ex As Exception
      Throw ex
    End Try
  End Sub

  Public Function GetOrganization() As String
    Try
      Return ContentManagerProxy.GetOrganization(TrackingID)
    Catch ex As Exception
      Throw ex
    End Try
  End Function

  Public Function GetOwnerTypes() As Dictionary(Of Integer, String)
    Try
      Return ContentManagerProxy.GetOwnerTypes(TrackingID)
    Catch ex As Exception
      Throw ex
    End Try
  End Function

  Public Function GetOwners(ByVal OwnerTypeID As Integer) As Dictionary(Of Integer, String)
    Try
      Return ContentManagerProxy.GetOwners(TrackingID, OwnerTypeID)
    Catch ex As Exception
      Throw ex
    End Try
  End Function

#End Region

End Class
