Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Language
Imports DigitalData.Modules.Logging

Namespace Methods.Database.GetDatatableFromCache
    Public Class GetDatatableFromCacheMethod
        Inherits BaseMethod

        Public Sub New(pLogConfig As LogConfig, pDatabaseIDB As MSSQLServer, pDatabaseECM As MSSQLServer, pGlobalState As GlobalState)
            MyBase.New(pLogConfig, pDatabaseIDB, pDatabaseECM, pGlobalState)
        End Sub

        Public Function Run(pData As GetDatatableFromCacheRequest) As GetDatatableFromCacheResponse
            Try
                Logger.Debug($"ReturnDatatableFromCache: Datatable: {pData.DataTable}")

                Dim oDataTable As DataTable = Nothing

                Logger.Debug("ReturnDatatableFromCache: DataSet contains [{0}] datatables", GlobalState.TableStore.Tables.Count)

                If GlobalState.TableStore.Tables.Contains(pData.DataTable) Then
                    oDataTable = GlobalState.TableStore.Tables.Item(pData.DataTable).Copy()

                    ' Apply filter and sorting to data
                    Dim oFilterExpression As String = Utils.NotNull(pData.FilterExpression, String.Empty)
                    Dim oSortByColumn As String = Utils.NotNull(pData.SortByColumn, String.Empty)

                    Dim oFilteredRows = oDataTable.Select(oFilterExpression, oSortByColumn)
                    Dim oFilteredTable As DataTable = Nothing

                    If oFilteredRows.Count > 0 Then
                        oFilteredTable = oFilteredRows.CopyToDataTable()
                        oFilteredTable.TableName = pData.DataTable
                    Else
                        ' Produce empty table
                        oFilteredTable = oDataTable.Clone()
                        oFilteredTable.TableName = pData.DataTable
                    End If

                    Logger.Debug("ReturnDatatableFromCache: Datatable Stats for [{0}]:", pData.DataTable)
                    Logger.Debug("Unfiltered: [{0}] rows", oDataTable.Rows.Count)
                    Logger.Debug("Filtered: [{0}] rows", oFilteredTable.Rows.Count)

                    Return New GetDatatableFromCacheResponse(oFilteredTable)
                Else
                    Logger.Warn($"ReturnDatatableFromCache: Datatable {pData.DataTable} does not exist")

                    Return New GetDatatableFromCacheResponse(New KeyNotFoundException($"Datatable {pData.DataTable} does not exist"))
                End If

            Catch ex As Exception
                Logger.Error(ex)
                Return New GetDatatableFromCacheResponse(ex)

            End Try
        End Function
    End Class

End Namespace