Imports System.Data.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Web.HttpContext
Imports System.Web
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.CommonEntities.Library.EntitySearch
Imports System.Xml





Public Class ProviderManager
    Inherits ISearchProvider


    Private _cmd As DbCommand
    Private _db As Database

    Public Sub New()
        Me.DB = DatabaseFactory.CreateDatabase("Charter.Website.WS.CommerceEngineConnectionString")

    End Sub
    'Public Sub New(ByVal configData As String)
    '    Dim args As XmlNode
    '    Dim xDoc As XmlDocument
    '    Try
    '        xDoc = New XmlDocument()
    '        xDoc.LoadXml(configData)
    '        args = xDoc.DocumentElement()
    '        If (Not args Is Nothing) AndAlso (Not args.ChildNodes(0) Is Nothing) AndAlso _
    '            (args.ChildNodes(0).LocalName = Constant.CONFIG_PROVIDERDATA) Then
    '            For Each providerData As XmlNode In args.ChildNodes(0).ChildNodes
    '                Select Case providerData.LocalName.ToUpper
    '                    Case Constant.CONFIG_CONNECTIONSTRING
    '                        Me.DB = DatabaseFactory.CreateDatabase(providerData.InnerText)
    '                    Case Else
    '                End Select
    '            Next
    '        Else
    '            Throw New Exception(Constant.EXCEPTION_CONFIGURATION)
    '        End If
    '    Catch ex As Exception
    '        Throw ex
    '    End Try
    'End Sub
    'Public Sub New(ByVal args As XmlNode)
    '  ''Try

    '  ''  If (Not args Is Nothing) AndAlso (Not args.ChildNodes(0) Is Nothing) AndAlso _
    '  ''                  (args.ChildNodes(0).LocalName = Constant.CONFIG_PROVIDERDATA) Then
    '  ''    For Each providerData As XmlNode In args.ChildNodes(0).ChildNodes
    '  ''      Select Case providerData.LocalName.ToUpper
    '  ''        Case Constant.CONFIG_CONNECTIONSTRING
    '  ''          Me.DB = DatabaseFactory.CreateDatabase(providerData.InnerText)
    '  ''        Case Else
    '  ''      End Select
    '  ''    Next
    '  ''  Else
    '  ''    Throw New Exception(Constant.EXCEPTION_CONFIGURATION)
    '  ''  End If
    '  ''Catch ex As Exception
    '  ''  Throw ex
    '  ''Finally


    '  ''End Try
    'End Sub
    Public Shared Function Instance() As ProviderManager
        'Try
        '    If Current.Session("ContentData") Is Nothing Then
        '        'If user instance does not exist, create one
        '        Current.Session("ContentData") = New ProviderManager()
        '        Return CType(Current.Session("ProviderManager"), ProviderManager)
        '    Else
        '        'If user instance already exists, return that
        '        Return CType(Current.Session("ProviderManager"), ProviderManager)
        '    End If
        'Catch ex As Exception
        '    Throw ex
        'Finally

        'End Try
        Return Nothing

    End Function
    Private Property DB() As Database
        Get
            Return _db
        End Get
        Set(ByVal value As Database)
            _db = value
        End Set
    End Property
    Private Property CMD() As DbCommand
        Get
            Return _cmd
        End Get
        Set(ByVal value As DbCommand)
            _cmd = value
        End Set
    End Property






    Public Overrides Function SearchSite(ByVal SearchString As String) As IProviderResults
        '##############################################
        Dim objResponse As New SearchSiteResponse
        '##############################################

        Try
            Dim command As DbCommand = DB.GetStoredProcCommand("SUPPORT.SEARCH_SITE")

            Dim Parameter1 As DbParameter = command.CreateParameter()
            With Parameter1
                .DbType = DbType.String
                .Direction = ParameterDirection.Input
                .ParameterName = "@SEARCHSTRING"
                .Value = HttpUtility.HtmlEncode(SearchString)
            End With
            command.Parameters.Add(Parameter1)


            Using dataReader As IDataReader = DB.ExecuteReader(command)
                '#########################################################################################
                'translate back to a common object in the gateway, visible from Provider and the BL both.
                '#########################################################################################
                objResponse.SearchResultCollection = New SearchResultCollection
                objResponse.SearchResultCollection.results = New List(Of SearchResult)
                While (dataReader.Read())
                    Dim lResult As New SearchResult
                    lResult.DocumentID = HttpUtility.HtmlDecode(dataReader("HTMLDOCUMENTID"))
                    lResult.ParentFolderID = HttpUtility.HtmlDecode(dataReader("DOCUMENTFOLDERID"))
                    lResult.Title = HttpUtility.HtmlDecode(dataReader("TITLE"))
                    lResult.Summary = HttpUtility.HtmlDecode(dataReader("SUMMARY"))

                    If Not (dataReader("BINARYDOCUMENTMIMETYPE") Is DBNull.Value) Then
                        lResult.BinaryDocumentMimeType = HttpUtility.HtmlDecode(dataReader("BINARYDOCUMENTMIMETYPE"))
                    End If

                    Select Case HttpUtility.HtmlDecode(dataReader("MIMETYPE").ToString())
                        Case "application/pdf"
                            lResult.MimeType = MimeType.PDF
                            lResult.URL = "GETBINARY.xbin?ID=" & lResult.DocumentID.ToString
                        Case "text/plain"
                            lResult.MimeType = MimeType.TXT
                            lResult.URL = "GETBINARY.xbin?ID=" & lResult.DocumentID.ToString
                        Case "application/msword"
                            lResult.MimeType = MimeType.DOC
                            lResult.URL = "GETBINARY.xbin?ID=" & lResult.DocumentID.ToString
                        Case "CONTENT"
                            lResult.MimeType = MimeType.CONTENT_ARTICLE_FROM_DB
                            If Not (dataReader("USERCONTROLID") Is DBNull.Value) Then
                                lResult.URL = dataReader("USERCONTROLID") & dataReader("HTMLDOCUMENTID") & "," & dataReader("OWNERID") & "," & dataReader("OWNERTYPEID")
                            Else
                                lResult.URL = dataReader("USERCONTROLID") & "," & dataReader("OWNERID") & "," & dataReader("OWNERTYPEID")
                            End If

                        Case Else
                            lResult.MimeType = MimeType.SUPPORT_ARTICLE_FROM_DB
                            lResult.URL = "../Visitors/Support.aspx?SupportArticleID=" & lResult.DocumentID.ToString
                    End Select

                    lResult.Score = HttpUtility.HtmlDecode(dataReader("SCORE"))
                    lResult.CreateDate = HttpUtility.HtmlDecode(dataReader("CREATEDATE"))

                    Select Case CInt(HttpUtility.HtmlDecode(dataReader("RESULTTYPE")))
                        Case 0
                            lResult.resultType = SearchResultType.Support
                        Case 1
                            lResult.resultType = SearchResultType.Site
                    End Select

                    objResponse.SearchResultCollection.results.Add(lResult)
                End While

                dataReader.Close()
            End Using


            Return objResponse

        Catch ex As Exception

            objResponse.Exception = True
            objResponse.ExceptionMessage = ex.Message
            objResponse.ExceptionStackTrace = ex.StackTrace
            Return objResponse
        Finally

        End Try

    End Function

    Public Overrides Function SearchSupport(ByVal SearchString As String) As IProviderResults
        '############################################## 
        Dim objResponse As New SearchSupportResponse
        '##############################################

        Try
            Dim command As DbCommand = DB.GetStoredProcCommand("SUPPORT.SEARCH_SUPPORT")

            Dim Parameter1 As DbParameter = command.CreateParameter()
            With Parameter1
                .DbType = DbType.String
                .Direction = ParameterDirection.Input
                .ParameterName = "@SEARCHSTRING"
                .Value = HttpUtility.HtmlEncode(SearchString)
            End With
            command.Parameters.Add(Parameter1)


            Using dataReader As IDataReader = DB.ExecuteReader(command)
                '#########################################################################################
                'translate back to a common object in the gateway, visible from Provider and the BL both.
                '#########################################################################################
                objResponse.SearchResultCollection = New SearchResultCollection
                objResponse.SearchResultCollection.results = New List(Of SearchResult)
                While (dataReader.Read())
                    Dim lResult As New SearchResult
                    lResult.DocumentID = HttpUtility.HtmlDecode(dataReader("HTMLDOCUMENTID"))
                    lResult.ParentFolderID = HttpUtility.HtmlDecode(dataReader("DOCUMENTFOLDERID"))
                    lResult.Title = HttpUtility.HtmlDecode(dataReader("TITLE"))
                    lResult.Summary = HttpUtility.HtmlDecode(dataReader("SUMMARY"))

                    If Not (dataReader("BINARYDOCUMENTMIMETYPE") Is DBNull.Value) Then
                        lResult.BinaryDocumentMimeType = HttpUtility.HtmlDecode(dataReader("BINARYDOCUMENTMIMETYPE"))
                    End If

                    Select Case HttpUtility.HtmlDecode(dataReader("MIMETYPE").ToString())
                        Case "application/pdf"
                            lResult.MimeType = MimeType.PDF
                            lResult.URL = "GETBINARY.xbin?ID=" & lResult.DocumentID.ToString
                        Case "text/plain"
                            lResult.MimeType = MimeType.TXT
                            lResult.URL = "GETBINARY.xbin?ID=" & lResult.DocumentID.ToString
                        Case "application/msword"
                            lResult.MimeType = MimeType.DOC
                            lResult.URL = "GETBINARY.xbin?ID=" & lResult.DocumentID.ToString
                        Case Else
                            lResult.MimeType = MimeType.SUPPORT_ARTICLE_FROM_DB
                            lResult.URL = "Support.aspx?SupportArticleID=" & lResult.DocumentID.ToString
                    End Select

                    lResult.Score = HttpUtility.HtmlDecode(dataReader("SCORE"))
                    lResult.CreateDate = HttpUtility.HtmlDecode(dataReader("CREATEDATE"))

                    Select Case CInt(HttpUtility.HtmlDecode(dataReader("RESULTTYPE")))
                        Case 0
                            lResult.resultType = SearchResultType.Support
                        Case 1
                            lResult.resultType = SearchResultType.Site
                    End Select

                    objResponse.SearchResultCollection.results.Add(lResult)
                End While

                dataReader.Close()
            End Using


            Return objResponse


        Catch ex As Exception
            objResponse.Exception = True
            objResponse.ExceptionMessage = ex.Message
            objResponse.ExceptionStackTrace = ex.StackTrace
            Return objResponse
        Finally

        End Try
    End Function

    Public Overrides Function GetSearchXml() As IProviderResults

        Dim objresult As EntityG2BServices.EntityUIRules
        objresult = New EntityG2BServices.EntityUIRules()
        Try

            objresult.Data = CType(System.Web.HttpContext.Current.Application("SEARCHXML"), String)
            Return (objresult)
        Catch ex As Exception
            objresult.Exception = True
            objresult.ExceptionMessage = ex.Message
            objresult.ExceptionStackTrace = ex.StackTrace
            Return (objresult)
        End Try
    End Function

    Public Overrides Function RegisterForUpdates(ByVal obj As CharterDotCom.CommonEntities.Library.IProviderParameters) As Boolean
        Try
            If Not obj Is Nothing Then
                Dim request As RegisterForUpdatesRequest
                request = CType(obj, RegisterForUpdatesRequest)
                CMD = DB.GetStoredProcCommand("CUSTOMER.REGISTRATION_ADD")
                DB.AddInParameter(CMD, "@FirstName", DbType.String, request.FirstName)
                DB.AddInParameter(CMD, "@LastName", DbType.String, request.LastName)
                DB.AddInParameter(CMD, "@Street", DbType.String, request.Street)
                DB.AddInParameter(CMD, "@Apt", DbType.String, request.Apt)
                DB.AddInParameter(CMD, "@City", DbType.String, request.City)
                DB.AddInParameter(CMD, "@State", DbType.String, request.State)
                DB.AddInParameter(CMD, "@Zip", DbType.String, request.Zip)
                DB.AddInParameter(CMD, "@Phone", DbType.String, request.Phone)
                DB.AddInParameter(CMD, "@Email", DbType.String, request.Email)
                DB.AddInParameter(CMD, "@TrackingID", DbType.String, request.TrackingID)
                DB.ExecuteNonQuery(CMD)
                Return True
            End If
            Return False
        Catch ex As Exception
            Throw New ApplicationException("Cannot Register customer at this time", ex)
        End Try
    End Function

End Class
