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

Namespace Methods.IDB.GetAttributeValue
    Public Class GetAttributeValueMethod
        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 GetAttributeValueRequest) As GetAttributeValueResponse
            Try
                If Helpers.TestObjectIdExists(pData.ObjectId) = False Then
                    LogAndThrow("ObjectId does not exist!")
                End If

                Dim oSQL As String = $"SELECT TERM_VALUE FROM FNIDB_GET_VARIABLE_VALUE ({pData.ObjectId}, '{pData.AttributeName}', '{pData.User.Language}')"
                Dim oTable As DataTable = DatabaseIDB.GetDatatable(oSQL)

                If oTable Is Nothing Then
                    Throw New ApplicationException($"Error while getting value for Attribute '{pData.AttributeName}'!")
                End If

                If oTable.Rows.Count = 0 Then
                    Throw New KeyNotFoundException($"Attribute '{pData.AttributeName}' is empty!")
                End If

                Dim oRow As DataRow = oTable.Rows.Item(0)
                Dim oValue As Object = oRow.Item("TERM_VALUE")

                Return New GetAttributeValueResponse(pData.ObjectId, oValue)

            Catch ex As Exception
                Logger.Warn("Error occurred while getting attribute value!")
                Logger.Error(ex)
                Return New GetAttributeValueResponse(ex)

            End Try
        End Function
    End Class
End Namespace