Imports System.Web.HttpContext
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 CharterDotCom.WebSite.Library
Imports System.Web


Public Class SiteManager

    Private _trackingID As String
    Private _sm As BLSiteManager

    Private Sub New()
        _sm = New BLSiteManager()

        _trackingID = HttpContext.Current.Session.SessionID


        'Try

        '  Common.RegisterChannels()
        '  SiteManagerProxy = CType(Activator.GetObject(GetType(SiteClient), CStr(HttpContext.Current.Application("RemoteURL_SiteManager"))), SiteClient)
        '  If Not HttpContext.Current.Request.Cookies(CookieName.SessionID) Is Nothing Then
        '    _trackingID = SiteManagerProxy.Initialize(HttpContext.Current.Request.Cookies(CookieName.SessionID).Value)
        '  Else
        '    _trackingID = SiteManagerProxy.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
            SiteManagerProxy.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 SiteManagerProxy() As BLSiteManager
        Get
            Return _sm
        End Get
        Set(ByVal value As BLSiteManager)
            _sm = value
        End Set
    End Property
    Public Shared Function Instance() As SiteManager
        Try
            'If Common.RetriveFromSession(Common.SiteManagerKey) Is Nothing Then
            '  'If user instance does not exist, create one
            '  Common.AddToSession((Common.SiteManagerKey), New SiteManager())
            '  Return CType(Common.RetriveFromSession(Common.SiteManagerKey), SiteManager)
            'Else
            '  'If user instance already exists, return that
            '  Return CType(Common.RetriveFromSession(Common.SiteManagerKey), SiteManager)
            'End If
            Return New SiteManager
        Catch ex As Exception
            Throw ex
        End Try
    End Function


#Region "SEARCHING"

    Public Function SearchSupport(ByVal SearchString As String) As ISearchResultCollection
        Try
            Return SiteManagerProxy.SearchSupport(SearchString)

        Catch ex As Exception
            Throw ex
        End Try
    End Function
    Public Function SearchSite(ByVal SearchString As String) As ISearchResultCollection
        Try
            Return SiteManagerProxy.SearchSite(SearchString)

        Catch ex As Exception
            Throw ex
        End Try
    End Function

#End Region

#Region "WEB CONFIGURATION SETTINGS SECTION"
    Public Function GetWebConfigSettings(ByVal RequestLocation As String) As IWebConfigSettingsCollection
        Try
            Return SiteManagerProxy.GetWebConfigSettings(RequestLocation)

        Catch ex As Exception
            Throw ex
        End Try
    End Function
#End Region


#Region "SUPPORT METHODS AND FUNCTIONS"

    Public Sub AddDocumentComments(ByVal obj As IAddDocumentCommentsRequest)
        Try
            SiteManagerProxy.AddDocumentComments(obj.Comments, obj.CreatedBy, obj.DocumentID, obj.Helpful, obj.Rating)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Function GetRelatedDocuments(ByVal ID As Integer) As IDocumentFolder
        Try
            Dim result As Dictionary(Of String, Object) = SiteManagerProxy.GetRelatedDocuments(ID)

            'Dim lOutList As New Dictionary(Of String, Object)
            'For Each item As Dictionary(Of String, Object) In result
            '    Dim lList As New BLHTMLDocument
            '    lList.ID = CInt(item(0))
            '    lList.Title = item(1).ToString()
            '    lOutList.Add(lList)
            'Next

            Dim lFolder As New BLDocumentFolder
            Dim lCnt As Integer = 0
            For Each item As Dictionary(Of String, Object) In result.Values
                Dim lList As New BLHTMLDocument
                lList.ID = CType(item("HTMLDOcumentID"), Integer)
                lList.Title = item("Title").ToString()

                If lFolder.ChildDocuments Is Nothing Then
                    lFolder.ChildDocuments = New Dictionary(Of String, BLHTMLDocument)
                End If

                lFolder.ChildDocuments.Add(lCnt.ToString(), lList)
                lCnt = lCnt + 1
            Next


            'Return lOutList
            Return lFolder


            'Return SiteManagerProxy.GetRelatedDocuments(ID)

        Catch ex As Exception
            Throw ex
        End Try
    End Function
    Public Sub RemoveDocumentRelation(ByVal ID As Integer, ByRef IDtoRemove As Integer)
        Try
            SiteManagerProxy.RemoveDocumentRelation(ID, IDtoRemove)

        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Function GetAllDocuments() As IDocumentFolder
        Try
            Dim result As Dictionary(Of String, Object) = SiteManagerProxy.GetAllDocuments()

            'Dim lOutList As New Dictionary(Of String, Object)
            'For Each item As Dictionary(Of String, Object) In result
            '    Dim lList As New BLHTMLDocument
            '    lList.ID = CInt(item(0))
            '    lList.Title = item(1).ToString()
            '    lOutList.Add(lList)
            'Next

            'Return lOutList

            Dim lFolder As New BLDocumentFolder
            Dim lCnt As Integer = 0
            For Each item As Dictionary(Of String, Object) In result.Values
                Dim lList As New BLHTMLDocument
                lList.ID = CType(item("HTMLDOcumentID"), Integer)
                lList.Title = item("Title").ToString()

                If lFolder.ChildDocuments Is Nothing Then
                    lFolder.ChildDocuments = New Dictionary(Of String, BLHTMLDocument)
                End If

                lFolder.ChildDocuments.Add(lCnt.ToString(), lList)
                lCnt = lCnt + 1
            Next

            Return lFolder
        Catch ex As Exception
            Throw ex
        End Try
    End Function
    Public Sub RelateDocument(ByVal ID As Integer, ByRef IDtoRelate As Integer)
        Try
            SiteManagerProxy.RelateDocument(ID, IDtoRelate)

        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Function AddDocument(ByVal folderID As Integer, ByRef obj As BLHTMLDocument) As Integer
        Try
            Return SiteManagerProxy.AddDocument(folderID, obj.HTML, obj.ID, obj.KeyWords, obj.Summary, obj.Title)

        Catch ex As Exception
            Throw ex
        End Try
    End Function
    Public Function AddFolder(ByRef obj As BLDocumentFolder) As Integer
        Try
            Return SiteManagerProxy.AddFolder(obj.ID, obj.Name, obj.NumberOfChildren, obj.ParentFolderID)
        Catch ex As Exception
            Throw ex
        End Try
    End Function
    Public Sub DeleteDocument(ByVal documentID As Integer)
        Try
            SiteManagerProxy.DeleteDocument(documentID)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Sub DeleteFolder(ByVal FolderID As Integer)
        Try
            SiteManagerProxy.DeleteFolder(FolderID)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Function GetDistinctKeyWords() As Dictionary(Of String, Object)
        Try
            Return SiteManagerProxy.GetDistinctKeyWords()
        Catch ex As Exception
            Throw ex
        End Try
    End Function
    Public Function GetDocument(ByVal documentID As Integer) As IHTMLDocument
        Try
            ' todo:dtb: For testing
            '             If HttpContext.Current.Cache("*CMSSupportArticle*" & documentID) Is Nothing Then
            If True Then
                '####################################################
                'DO THE REMOTING CALL TO PROVIDER TO GET THE RECORD
                '####################################################
                Dim result As Dictionary(Of String, Object) = SiteManagerProxy.GetDocument(documentID)
                Dim document As New BLHTMLDocument




                If result IsNot Nothing AndAlso result.ContainsKey("HTMLDocumentID") Then
                    document.ID = CType(result("HTMLDocumentID").ToString(), Integer)
                Else
                    '############################################################################################################
                    'ROD COPELAND   ISSUE ID 7819   7/28/2010
                    'REDIRECT USER TO THE MAIN PAGE AS SOMEONE IS ASKING FOR A ARTICLE ID THAT DOES NOT EXIST IN THE DB ANYMORE.
                    'RETURNING NOTHING HERE WILL PROMPT THE CALLING PAGE TO DO THE REDIRECT.
                    '############################################################################################################
                    Return Nothing
                End If




                If result.ContainsKey("HTML") Then
                    If Not (result("HTML") Is Nothing) Then
                        document.HTML = result("HTML").ToString()
                    Else
                        document.HTML = ""
                    End If
                Else
                    document.HTML = ""
                End If

                If result.ContainsKey("Keywords") Then
                    If Not (result("Keywords") Is Nothing) Then
                        document.KeyWords = result("Keywords").ToString()
                    Else
                        document.KeyWords = ""
                    End If
                Else
                    document.KeyWords = ""
                End If
                If result.ContainsKey("Summary") Then
                    If Not (result("Summary") Is Nothing) Then
                        document.Summary = result("Summary").ToString()
                    Else
                        document.Summary = ""
                    End If
                Else
                    document.Summary = ""
                End If
                If result.ContainsKey("Title") Then
                    If Not (result("Title") Is Nothing) Then
                        document.Title = result("Title").ToString()
                    Else
                        document.Title = ""
                    End If
                Else
                    document.Title = ""
                End If


                '########################################
                'SET THE EXPIRATION DATE THAT THE CACHE 
                'ITEM SHOULD REMOVE ITSELF AT
                '########################################

                '#####################################################################
                '#####################################################################
                Dim expiredate As DateTime
                Dim lNumOfDaysToCache As Integer = 2
                Dim lNumOfHoursToCache As Integer = 3


                '##########################################################
                'GET THE DAYS TO CACH VALUE FROM DB TABLE ADMIN.WEBCONFIG
                '##########################################################
                If HttpContext.Current.Application("NUM_OF_DAYS_TO_CACHE") Is Nothing Then
                    lNumOfDaysToCache = 2
                Else
                    Try
                        lNumOfDaysToCache = CType(HttpContext.Current.Application("NUM_OF_DAYS_TO_CACHE"), Integer)
                    Catch ex As Exception
                        lNumOfDaysToCache = 2
                    End Try
                End If

                '##########################################################
                'GET THE HOURS TO CACH VALUE FROM DB TABLE ADMIN.WEBCONFIG
                '##########################################################
                If HttpContext.Current.Application("NUM_OF_HOURS_TO_CACHE") Is Nothing Then
                    lNumOfHoursToCache = 3
                Else
                    Try
                        lNumOfHoursToCache = CType(HttpContext.Current.Application("NUM_OF_HOURS_TO_CACHE"), Integer)
                    Catch ex As Exception
                        lNumOfHoursToCache = 3
                    End Try
                End If

                If Now() > Date.Today.AddHours(3) Then
                    expiredate = Date.Today.AddDays(lNumOfDaysToCache).AddHours(lNumOfHoursToCache)
                Else
                    expiredate = Date.Today.AddHours(lNumOfHoursToCache)
                End If
                '#####################################################################
                '#####################################################################




                '###########################################################################
                '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()
                '############################################################################
                HttpContext.Current.Cache.Insert("*CMSSupportArticle*" & documentID, document, Nothing, expiredate, Caching.Cache.NoSlidingExpiration, Caching.CacheItemPriority.AboveNormal, Nothing)


                Return document
            Else
                '###############################
                'RETURN THE VALUE FROM CACHE
                '###############################
                Return CType(HttpContext.Current.Cache("*CMSSupportArticle*" & documentID), BLHTMLDocument)
            End If

        Catch ex As Exception
            Return Nothing
        End Try

    End Function
    Public Function GetEligibility(ByVal account As String, ByVal mac As String, ByVal phone As String, ByVal zipAccount As String, ByVal zipPhone As String) As String
        Try
            Dim result As String = SiteManagerProxy.GetEligibility(account, mac, phone, zipAccount, zipPhone)
            Return result
        Catch ex As Exception
            Return "Error: Can't retrieve eligibility"
        End Try
    End Function
    Public Function GetDocumentFolders() As IDocumentFolder
        Try
            Dim Folders As Dictionary(Of String, Object) = SiteManagerProxy.GetDocumentFolders()

            Dim outList As New BLDocumentFolder
            Dim lCnt As Integer = 0
            For Each obj As Dictionary(Of String, Object) In Folders.Values
                Dim folder As New BLDocumentFolder
                folder.ID = CInt(obj("DocumentFolderID"))
                folder.Name = obj("DocumentFolderName").ToString()

                If outList.ChildFolders Is Nothing Then
                    outList.ChildFolders = New Dictionary(Of String, BLDocumentFolder)
                End If

                outList.ChildFolders.Add(lCnt.ToString(), folder)
                lCnt = lCnt + 1
            Next

            Return outList

        Catch ex As Exception
            Throw ex
        End Try
    End Function

    ' get all support folders 
    Public Function GetAllFolders() As List(Of CachedFolder)
        Dim folderTable As DataTable
        Dim list As New List(Of CachedFolder)
        Dim folder As CachedFolder
        folderTable = SiteManagerProxy.GetAllFolders
        If folderTable IsNot Nothing Then
            For Each row As DataRow In folderTable.Rows
                folder.ID = CInt(row("DocumentFolderID"))
                folder.Name = CStr(row("DocumentFolderName"))
                folder.ParentID = CInt(row("ParentFolderID"))
                list.Add(folder)
            Next
        End If
        Return list
    End Function

    Public Function GetDocumentFolders(ByVal parentFolderID As Integer) As IDocumentFolder
        Try

            Dim Folders As Dictionary(Of String, Object)
            Dim cacheEntry As Object
            Dim supportCache As List(Of CachedFolder)
            Dim outList As New BLDocumentFolder
            Dim childFolder As BLDocumentFolder
            cacheEntry = HttpContext.Current.Cache(CharterDotCom.CommonEntities.Library.Common.m_SUPPORT_CACHE)

            If cacheEntry IsNot Nothing Then
                ' get from cache
                supportCache = CType(cacheEntry, List(Of CachedFolder))
                outList.ID = parentFolderID
                Dim count As Integer = 0
                If outList.ChildFolders Is Nothing Then
                    outList.ChildFolders = New Dictionary(Of String, BLDocumentFolder)
                End If
                For Each folder As CachedFolder In supportCache
                    If folder.ID = parentFolderID Then
                        outList.Name = folder.Name
                    End If
                    If folder.ParentID = parentFolderID Then
                        childFolder = New BLDocumentFolder()
                        childFolder.ID = folder.ID
                        childFolder.Name = folder.Name
                        outList.ChildFolders.Add(count.ToString, childFolder)
                        count += 1
                    End If
                Next
            Else

                Folders = SiteManagerProxy.GetDocumentFolders(parentFolderID)

                Dim lCnt As Integer = 0
                For Each obj As Dictionary(Of String, Object) In Folders.Values
                    Dim folder As New BLDocumentFolder
                    folder.ID = CInt(obj("DocumentFolderID"))
                    folder.Name = obj("DocumentFolderName").ToString()
                    folder.NumberOfChildren = CInt(obj("NumberOfChildren"))

                    If outList.ChildFolders Is Nothing Then
                        outList.ChildFolders = New Dictionary(Of String, BLDocumentFolder)
                    End If

                    outList.ChildFolders.Add(lCnt.ToString(), folder)
                    lCnt = lCnt + 1
                Next

            End If

            Return outList

            'Return SiteManagerProxy.GetDocumentFolders(parentFolderID)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function GetFolder(ByVal folderID As Integer) As IDocumentFolder
        Try
            Dim result As Dictionary(Of String, Object)
            Dim folder As New BLDocumentFolder
            Dim cacheEntry As Object
            cacheEntry = HttpContext.Current.Cache(CharterDotCom.CommonEntities.Library.Common.m_SUPPORT_CACHE)
            Dim supportCache As List(Of CachedFolder)

            If cacheEntry Is Nothing Then
                result = SiteManagerProxy.GetFolder(folderID)

                folder.ID = CInt(result("DocumentFolderID"))
                folder.Name = result("DocumentFolderName").ToString()
                folder.ParentFolderID = CInt(result("ParentFolderID"))
                Return folder
            Else
                ' get from cache
                supportCache = CType(cacheEntry, List(Of CachedFolder))
                For Each cf As CachedFolder In supportCache
                    If cf.ID = folderID Then
                        folder.ID = cf.ID
                        folder.Name = cf.Name
                        folder.ParentFolderID = cf.ParentID
                        Return folder
                    End If
                Next
            End If

            Return Nothing

        Catch ex As Exception
            Throw ex
        End Try
    End Function



    Public Sub MoveDocument(ByVal documentID As Integer, ByVal newFolderID As Integer)
        Try
            SiteManagerProxy.MoveDocument(documentID, newFolderID)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Sub UpdateDocument(ByRef obj As BLHTMLDocument)
        Try
            SiteManagerProxy.UpdateDocument(obj.HTML, obj.ID, obj.KeyWords, obj.Summary, obj.Title)

        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Sub UpdateFolder(ByRef obj As BLDocumentFolder)
        Try
            SiteManagerProxy.UpdateFolder(obj.ID, obj.Name, obj.NumberOfChildren, obj.ParentFolderID)

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region



#Region "Populate Channel Line Up (CLU) Functions"

    Public Function GetChannelLineup(ByVal AddressLine1 As String, ByVal AddressLine2 As String, ByVal ZipCode As String, ByVal HDTVOnly As Boolean) As IChannelLineUp
        Try
            Return SiteManagerProxy.GetChannelLineup(TrackingID, AddressLine1, AddressLine2, ZipCode, HDTVOnly)
        Catch ex As Exception
            Throw ex
        End Try

    End Function

    Public Sub GetLineupBySystemFTA(ByVal FTA As String, ByVal SystemCode As String)
        Try
            SiteManagerProxy.GetLineupBySystemFTA(TrackingID, FTA, SystemCode)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub GetLineupByZipZip4(ByVal Zip As String, ByVal Zip4 As String)
        Try
            SiteManagerProxy.GetLineupByZipZip4(TrackingID, Zip, Zip4)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region

#Region "CONTACT US"

    Public Function ContactUsByEmail(ByVal fName As String, ByVal lName As String, ByVal streetAddress As String, ByVal city As String, ByVal state As String, ByVal zip As String, ByVal phoneNumber As String, ByVal fromEmail As String, ByVal subject As String, ByVal body As String) As Boolean
        Try
            Return SiteManagerProxy.ContactUsByEmail(TrackingID, fName, lName, streetAddress, city, state, zip, phoneNumber, fromEmail, subject, body)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

#End Region

#Region "OTHER"

    Public Sub SubscribeForUpdates(ByVal eMail As String, ByVal cable As Boolean, ByVal data As Boolean, ByVal voice As Boolean)
        Try
            SiteManagerProxy.SubscribeForUpdates(TrackingID, eMail, cable, data, voice)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Function GetSearchXML() As String
        Try
            Return SiteManagerProxy.GetSearchXml(TrackingID)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function GetKey() As String
        Try
            Return (SiteManagerProxy.GetKey(TrackingID))
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Sub SetKey(ByVal SiteKey As String)
        Try
            SiteManagerProxy.SetKey(TrackingID, SiteKey)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region

#Region "Register for Services"

    Public Function PreRegisterForUpdate(ByVal fName As String, ByVal lname As String, _
           ByVal street As String, ByVal apt As String, ByVal city As String, ByVal state As String, ByVal zip As String, ByVal phone As String, ByVal email As String) As Boolean
        Try
            Return SiteManagerProxy.PreRegisterForUpdate(TrackingID, fName, lname, street, apt, city, state, zip, phone, email)
        Catch ex As Exception
            Throw ex
        End Try
    End Function


    Public Function RequestForFollowUp(ByVal fName As String, ByVal lname As String, _
        ByVal street As String, ByVal apt As String, ByVal city As String, ByVal state As String, ByVal zip As String, _
        ByVal phone As String, ByVal email As String, ByVal cable As Boolean, ByVal hsd As Boolean, ByVal telephone As Boolean) As Boolean
        Try
            Return SiteManagerProxy.RequestForFollowUp(TrackingID, fName, lname, street, apt, city, state, zip, phone, email, cable, hsd, telephone)
        Catch ex As Exception
            Throw ex
        End Try
    End Function

#End Region

End Class
