Imports DigitalData.Modules.Database
Imports DigitalData.Modules.EDMI.API
Imports DigitalData.Modules.EDMI.API.EDMIServiceReference
Imports DigitalData.Modules.Logging

Public Class MSSQLServerCached
    Private _Logger As Logger
    Private _Client As Client
    Private _DatabaseEDM As MSSQLServer
    Private _DatabaseIDB As MSSQLServer
    Private _Type As DatabaseType

    Public Enum DatabaseType
        ECM
        IDB
    End Enum

    Public Sub New(LogConfig As LogConfig, Client As Client, DatabaseECM As MSSQLServer, DatabaseIDB As MSSQLServer)
        _Logger = LogConfig.GetLogger()
        _Client = Client
        _DatabaseEDM = DatabaseECM
        _DatabaseIDB = DatabaseIDB
    End Sub

    Public Function GetDatatable(DataTable As String, FilterExpression As String, SortByColumn As String, FallbackSQL As String, FallbackType As DatabaseType, Optional ForceFallback As Boolean = False) As DataTable
        Try
            Dim oResult As DataTable = Nothing

            If ForceFallback = False Then
                Dim oTableResult As TableResult = _Client.GetDatatableByName(DataTable, FilterExpression, SortByColumn)

                If oTableResult Is Nothing OrElse oTableResult.OK = False Then
                    _Logger.Warn("Datatable [{0}] could not be fetched from AppServer Cache. Falling back to direct Database Access.")
                End If
            Else
                Return GetDatatableFromDatabase(FallbackSQL, FallbackType)
            End If
        Catch ex As Exception
            _Logger.Error(ex)
            Return Nothing
        End Try
    End Function

    Private Function GetDatatableFromDatabase(SQLCommand As String, DatabaseType As DatabaseType)
        Try
            Select Case DatabaseType
                Case DatabaseType.ECM
                    Return _DatabaseEDM.GetDatatable(SQLCommand)

                Case DatabaseType.IDB
                    Return _DatabaseIDB.GetDatatable(SQLCommand)

                Case Else
                    Return Nothing

            End Select
        Catch ex As Exception
            _Logger.Error(ex)
            Return Nothing

        End Try
    End Function
End Class
