Imports System.Data.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Web.HttpContext
Imports System.Web
Imports System.Net.Mail
Imports System.Xml
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.CommonEntities.Library.EntitySupport


Public Class ProviderManager
    Inherits IErrorMappingProvider


    Private _cmd As DbCommand
    Private _db As Database

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

    Public Shared Function Instance() As ProviderManager
        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


    Private Sub SendEMail(ByVal FromMailID As String, ByVal ToMailID As String, ByVal Subject As String, ByVal Body As String, Optional ByVal isHTML As Boolean = False)
        Try
            Dim from_Config As String = CType(HttpContext.Current.Application("SMTP_SERVER"), String)
            Dim client As New SmtpClient(from_Config)
            Dim mailMsg As New MailMessage(FromMailID, ToMailID)
            With mailMsg
                .Subject = Subject
                .Body = Body
            End With
            mailMsg.IsBodyHtml = isHTML
            client.Send(mailMsg)

        Catch ex As Exception

        End Try
    End Sub

    Private Sub AddNewError(ByVal DataSourceName As String, ByVal DataSourceLocation As String, ByVal DataSourceErrorCode As String, ByVal DataSourceErrorMessage As String, ByVal CCOMRelatedErrorCode As String, ByVal CCOMDisplayMessage As String)
        Dim retCode As Integer
        Try
            Me.CMD = Me.DB.GetStoredProcCommand("ADMIN.ADD_NEW_ERROR_RECORD_ON_DEMAND_FROM_CHARTERDOTCOM")

            If Not (DataSourceName Is Nothing) Then
                If DataSourceName.Trim().Length() > 0 Then
                    Me.DB.AddInParameter(CMD, "@DATA_SOURCE_NAME", DbType.String, DataSourceName)
                Else
                    Me.DB.AddInParameter(CMD, "@DATA_SOURCE_NAME", DbType.String, System.DBNull.Value)
                End If
            Else
                Me.DB.AddInParameter(CMD, "@DATA_SOURCE_NAME", DbType.String, System.DBNull.Value)
            End If
            If Not (DataSourceName Is Nothing) Then
                If DataSourceName.Trim().Length() > 0 Then
                    Me.DB.AddInParameter(CMD, "@DATA_SOURCE_LOCATION", DbType.String, DataSourceLocation)
                Else
                    Me.DB.AddInParameter(CMD, "@DATA_SOURCE_LOCATION", DbType.String, System.DBNull.Value)
                End If
            Else
                Me.DB.AddInParameter(CMD, "@DATA_SOURCE_LOCATION", DbType.String, System.DBNull.Value)
            End If
            If Not (DataSourceName Is Nothing) Then
                If DataSourceName.Trim().Length() > 0 Then
                    Me.DB.AddInParameter(CMD, "@DATA_SOURCE_ERROR_CODE", DbType.String, DataSourceErrorCode)
                Else
                    Me.DB.AddInParameter(CMD, "@DATA_SOURCE_ERROR_CODE", DbType.String, System.DBNull.Value)
                End If
            Else
                Me.DB.AddInParameter(CMD, "@DATA_SOURCE_ERROR_CODE", DbType.String, System.DBNull.Value)
            End If
            If Not (DataSourceName Is Nothing) Then
                If DataSourceName.Trim().Length() > 0 Then
                    Me.DB.AddInParameter(CMD, "@DATA_SOURCE_ERROR_MESSAGE", DbType.String, DataSourceErrorMessage)
                Else
                    Me.DB.AddInParameter(CMD, "@DATA_SOURCE_ERROR_MESSAGE", DbType.String, System.DBNull.Value)
                End If
            Else
                Me.DB.AddInParameter(CMD, "@DATA_SOURCE_ERROR_MESSAGE", DbType.String, System.DBNull.Value)
            End If
            If Not (DataSourceName Is Nothing) Then
                If DataSourceName.Trim().Length() > 0 Then
                    Me.DB.AddInParameter(CMD, "@CCOM_RELATED_ERROR_CODE", DbType.String, DataSourceErrorCode)
                Else
                    Me.DB.AddInParameter(CMD, "@CCOM_RELATED_ERROR_CODE", DbType.String, System.DBNull.Value)
                End If
            Else
                Me.DB.AddInParameter(CMD, "@CCOM_RELATED_ERROR_CODE", DbType.String, System.DBNull.Value)
            End If
            If Not (DataSourceName Is Nothing) Then
                If DataSourceName.Trim().Length() > 0 Then
                    Me.DB.AddInParameter(CMD, "@CCOM_DISPLAY_MESSAGE", DbType.String, DataSourceErrorMessage)
                Else
                    Me.DB.AddInParameter(CMD, "@CCOM_DISPLAY_MESSAGE", DbType.String, System.DBNull.Value)
                End If
            Else
                Me.DB.AddInParameter(CMD, "@CCOM_DISPLAY_MESSAGE", DbType.String, System.DBNull.Value)
            End If

            retCode = DB.ExecuteNonQuery(CMD)



            '################################################################################
            'SEND THE EMAIL NOTIFICATION THAT A NEW ERROR WAS ADDED SO SOMEONE CAN LOGIN AND 
            'UPDATE THE DISPLAY MESSAGE FOR CHARTERDOTCOM
            '################################################################################
            Me.SendEMail(HttpContext.Current.Application("EXCEPTION_EMAIL_SENDER"), HttpContext.Current.Application("EXCEPTION_MAIL_RECEIVER"), "A NEW EXCEPTION RECORD WAS ADDED FROM - " & Environment.MachineName.ToLower, "A NEW EXCEPTION RECORD WAS ADDED FROM - " & Environment.MachineName.ToLower & ".  Please find the table and update the Charter.com friendly display message. <br> ERROR CODE: " & DataSourceErrorCode & "<BR> ERROR MESSAGE: " & DataSourceErrorMessage, True)


        Catch ex As Exception
            'Throw ex
        Finally
            If Not CMD Is Nothing Then
                CMD.Dispose()
            End If
        End Try
    End Sub


    Public Function GetErrorMessageList(ByVal strDataSourceName As String, ByVal aryErrorList As Object, ByVal strErrorMessage As String) As String

        If Not (strDataSourceName Is Nothing) Then
            Select Case strDataSourceName.Trim().ToUpper()
                Case "CONTENTPROVIDER"

                Case "EBSSERVICESPROVIDER"

                Case "G2BSERVICESPROVIDER"
                    Dim X As String = CType(aryErrorList, String)
                    Return GetErrorMessageList_MEMBERSERVICESPROVIDER(strDataSourceName, X, strErrorMessage)
                Case "MEMBERSERVICESPROVIDER"
                    Dim X As String = CType(aryErrorList, String)
                    Return GetErrorMessageList_MEMBERSERVICESPROVIDER(strDataSourceName, X, strErrorMessage)
                Case "MEMBERSERVICES"
                    Dim X As String = CType(aryErrorList, String)
                    Return GetErrorMessageList_MEMBERSERVICESPROVIDER(strDataSourceName, X, strErrorMessage)
                Case "SEARCHPROVIDER"

                Case "SUPPORTPROVIDER"

                Case "WEBCONFIGPROVIDER"

                Case Else
                    Return Nothing
            End Select
        Else
            Return Nothing
        End If

        Return Nothing
    End Function


    Private Function GetErrorMessageList_MEMBERSERVICESPROVIDER(ByVal strDataSourceName As String, ByVal commaDelimitedErrorCodes As String, ByVal strErrorMessage As String) As String
        Try
            If commaDelimitedErrorCodes Is Nothing Then
                Return Nothing
            End If

            Dim outErrorList() As String
            Dim outErrorListString As String
            If Not (commaDelimitedErrorCodes Is Nothing) Then
                If commaDelimitedErrorCodes.Trim <> "" Then
                    Dim errorCodesArray() As String = commaDelimitedErrorCodes.Split(",")
                    If Not (errorCodesArray Is Nothing) Then


                        '###########################################################################################
                        'THE VALUE IN HttpContext.Current.Application("ERROR_CODE_MAPPING_COLLECTION") IS CREATED
                        'IN THE APPLICATION START EVENT IN THE GLOBAL.ASAX.VB
                        '###########################################################################################
                        Dim lErrorCodesCollection As Dictionary(Of String, ErrorCodes.ErrorMapRecord) = HttpContext.Current.Application("ERROR_CODE_MAPPING_COLLECTION")

                        ReDim outErrorList(errorCodesArray.GetUpperBound(0))
                        For i As Integer = 0 To errorCodesArray.GetUpperBound(0)
                            '############################################################
                            'COMPARE TO LIST OF ERROR POSSIBILITIES PROVIDED BY THE 
                            'DATASOURCE, IE MEMBERSERVICES, EBS, G2B, ECT.
                            '############################################################
                            If lErrorCodesCollection.ContainsKey(strDataSourceName & errorCodesArray(i).Trim()) Then
                                '##############################################################################
                                'IF THE CHARTER.COM ERROR MESSAGE IS NOT AVAILABLE THEN USE THE DATASOURCE 
                                'ERROR MESSAGE AND SEND A INDICATOR AS TO WHICH ONE IS BEING USED.
                                '##############################################################################
                                Select Case True
                                    Case Not lErrorCodesCollection(strDataSourceName & errorCodesArray(i).Trim()).ccomDisplayMessage Is Nothing
                                        '##############################
                                        'USE CHARTER.COM ERROR MESSAGE
                                        '##############################
                                        outErrorList(i) = lErrorCodesCollection(strDataSourceName & errorCodesArray(i).Trim()).ccomDisplayMessage
                                    Case Not lErrorCodesCollection(strDataSourceName & errorCodesArray(i).Trim()).dataSourceErrorMessage Is Nothing
                                        '##############################
                                        'USE DATA SOURCE ERROR MESSAGE
                                        '##############################
                                        outErrorList(i) = lErrorCodesCollection(strDataSourceName & errorCodesArray(i).Trim()).dataSourceErrorMessage
                                    Case Else
                                        '##################################################################################
                                        'ERROR WAS IN THE KNOWN COLLECTION BUT DIDNT HAVE A MESSAGE DEFINED BY THE DATASOURCE 
                                        'PROVIDER OR CHARTERDOTCOM.  THIS COULD BE A SITATION WHERE THE FIRST TIME I TRY 
                                        'SOMETHING I GENERATE SOMETYPE OF ERROR THAT IS NOT KNOWN TO THE ERROR MAPPING TABLE, 
                                        'THIS ERROR NUMBER WILL GET LOGGED ALONG WITH THE DATASOURCE VALUE.  NEXT TIME I 
                                        'GET THAT ERROR, IT SHOULD THEN BE IN THE COLLECTION OF KNOWN ERRORS, JUST WOULD 
                                        'HAVE NO VALUE FOR THE DATASOURCE MESSAGE OR THE CHARTERDOTCOM (CCOM) MESSAGE.  
                                        'IN THIS CASE JUST RETURN THE BASIC MESSAGE: 
                                        '"Sorry, we are unable to handle your request at this time."
                                        '##################################################################################
                                        outErrorList(i) = "Sorry, we are unable to handle your request at this time."
                                End Select
                            Else
                                'Dim strErrorCodesCollection As String = "<br><br><br><br><b>ERROR CODES COLLECTION</b><br><table>"
                                'strErrorCodesCollection = strErrorCodesCollection & "<tr>"
                                'strErrorCodesCollection = strErrorCodesCollection & "<td><b>KVP Key</b></td>"
                                'strErrorCodesCollection = strErrorCodesCollection & "<td><b>DB_ID</b></td>"
                                'strErrorCodesCollection = strErrorCodesCollection & "<td><b>dataSourceName</b></td>"
                                'strErrorCodesCollection = strErrorCodesCollection & "<td><b>dataSourceErrorCode</b></td>"
                                'strErrorCodesCollection = strErrorCodesCollection & "<td width='100'><b>dataSourceErrorMessage</b></td>"
                                'strErrorCodesCollection = strErrorCodesCollection & "<td><b>createDate</b></td>"
                                'strErrorCodesCollection = strErrorCodesCollection & "<td width='100'><b>ccomDisplayMessage</b></td>"
                                'strErrorCodesCollection = strErrorCodesCollection & "</tr>"
                                'For Each kvp As KeyValuePair(Of String, ErrorCodes.ErrorMapRecord) In lErrorCodesCollection
                                '    strErrorCodesCollection = strErrorCodesCollection & "<tr>"
                                '    strErrorCodesCollection = strErrorCodesCollection & "<td>" & kvp.Key & "</td>"
                                '    strErrorCodesCollection = strErrorCodesCollection & "<td>" & kvp.Value.DB_ID & "</td>"
                                '    strErrorCodesCollection = strErrorCodesCollection & "<td>" & kvp.Value.dataSourceName & "</td>"
                                '    strErrorCodesCollection = strErrorCodesCollection & "<td>" & kvp.Value.dataSourceErrorCode & "</td>"
                                '    strErrorCodesCollection = strErrorCodesCollection & "<td>" & kvp.Value.dataSourceErrorMessage & "</td>"
                                '    strErrorCodesCollection = strErrorCodesCollection & "<td>" & kvp.Value.createDate & "</td>"
                                '    strErrorCodesCollection = strErrorCodesCollection & "<td>" & kvp.Value.ccomDisplayMessage & "</td>"
                                '    strErrorCodesCollection = strErrorCodesCollection & "</tr>"
                                'Next
                                'strErrorCodesCollection = strErrorCodesCollection & "</table>"


                                '###############################################################
                                'add the new message to DB
                                'CURRENT STATE AT ROLLOUT, ADD THE SAME MESSAGE FOR ALL ERRRORS 
                                'RETURNED IN THE ERROR COLLECTION.
                                '###############################################################
                                Me.AddNewError(strDataSourceName, Nothing, errorCodesArray(i), strErrorMessage, Nothing, Nothing)


                                '#################################################################################
                                'UPDATE THE ERROR CODE MAPPING COLLECTION STORED IN THE APPLICATION OBJECT SO WE 
                                'HAVE THE CURRENT ERROR LIST TO USE.
                                '#################################################################################
                                Call UpdateErrorMappingCollection()


                                outErrorList(i) = "Sorry, we are unable to handle your request at this time."


                            End If
                        Next
                    End If
                End If
            End If

            If Not (outErrorList Is Nothing) Then
                If outErrorList.GetUpperBound(0) = 0 Then
                    '###############################################################
                    'IF THIS IS THE ONLY MESSAGE, DONT INSERT LINE BREAKS
                    '###############################################################
                    outErrorListString = outErrorList(0)
                Else
                    '###############################################################
                    'THERE ARE MULTIPLE MESSAGES, SHOW LINE BREAKS IN BETWEEN THEM
                    '###############################################################
                    For i As Integer = 0 To outErrorList.GetUpperBound(0)
                        If Not (outErrorList(i) Is Nothing) Then
                            outErrorListString = outErrorListString & outErrorList(i)
                        End If
                    Next
                End If


                'Return outErrorList
            End If
            Return outErrorListString
        Catch ex As Exception
            Return Nothing
        End Try
 


    End Function



    Private Sub UpdateErrorMappingCollection()

        Dim strSQL As String = "SELECT * FROM Admin.ERROR_CODE_MAPPING"
        Me.CMD = Me.DB.GetSqlStringCommand(strSQL)
        Dim DS As DataSet = DB.ExecuteDataSet(Me.CMD)


        Dim lErrorCodesCollection As New Dictionary(Of String, CharterDotCom.CommonEntities.Library.ErrorCodes.ErrorMapRecord)

        For Each row As Data.DataRow In DS.Tables(0).Rows
            Dim lErrorMapRecord As New CharterDotCom.CommonEntities.Library.ErrorCodes.ErrorMapRecord
            If Not (row.Item("ID") Is System.DBNull.Value) Then
                If Not (row.Item("ID") Is Nothing) Then
                    lErrorMapRecord.DB_ID = CType(row.Item("ID"), Integer)
                End If
            End If
            If Not (row.Item("DATA_SOURCE_NAME") Is System.DBNull.Value) Then
                If Not (row.Item("DATA_SOURCE_NAME") Is Nothing) Then
                    lErrorMapRecord.dataSourceName = CType(row.Item("DATA_SOURCE_NAME"), String)
                End If
            End If
            If Not (row.Item("DATA_SOURCE_LOCATION") Is System.DBNull.Value) Then
                If Not (row.Item("DATA_SOURCE_LOCATION") Is Nothing) Then
                    lErrorMapRecord.dataSourceLocation = CType(row.Item("DATA_SOURCE_LOCATION"), String)
                End If
            End If
            If Not (row.Item("DATA_SOURCE_ERROR_CODE") Is System.DBNull.Value) Then
                If Not (row.Item("DATA_SOURCE_ERROR_CODE") Is Nothing) Then
                    lErrorMapRecord.dataSourceErrorCode = CType(row.Item("DATA_SOURCE_ERROR_CODE"), String)
                End If
            End If
            If Not (row.Item("DATA_SOURCE_ERROR_MESSAGE") Is System.DBNull.Value) Then
                If Not (row.Item("DATA_SOURCE_ERROR_MESSAGE") Is Nothing) Then
                    lErrorMapRecord.dataSourceErrorMessage = CType(row.Item("DATA_SOURCE_ERROR_MESSAGE"), String)
                End If
            End If
            If Not (row.Item("CCOM_RELATED_ERROR_CODE") Is System.DBNull.Value) Then
                If Not (row.Item("CCOM_RELATED_ERROR_CODE") Is Nothing) Then
                    lErrorMapRecord.ccomRelatedErrorCode = CType(row.Item("CCOM_RELATED_ERROR_CODE"), String)
                End If
            End If
            If Not (row.Item("CCOM_DISPLAY_MESSAGE") Is System.DBNull.Value) Then
                If Not (row.Item("CCOM_DISPLAY_MESSAGE") Is Nothing) Then
                    lErrorMapRecord.ccomDisplayMessage = CType(row.Item("CCOM_DISPLAY_MESSAGE"), String)
                End If
            End If
            If Not (row.Item("CREATE_DATE") Is System.DBNull.Value) Then
                If Not (row.Item("CREATE_DATE") Is Nothing) Then
                    lErrorMapRecord.createDate = CType(row.Item("CREATE_DATE"), Date)
                End If
            End If

            lErrorCodesCollection.Add(lErrorMapRecord.dataSourceName & lErrorMapRecord.dataSourceErrorCode, lErrorMapRecord)
        Next

        HttpContext.Current.Application.Lock()
        HttpContext.Current.Application.Remove("ERROR_CODE_MAPPING_COLLECTION")
        HttpContext.Current.Application.Add("ERROR_CODE_MAPPING_COLLECTION", lErrorCodesCollection)
        HttpContext.Current.Application.UnLock()
    End Sub


End Class
