Imports DigitalData.Modules.EDMI.API
Imports DigitalData.Modules.EDMI.API.Constants
Imports DigitalData.Modules.Logging

Public Class ClassIDBData
    Public Property DTVWIDB_BE_ATTRIBUTE As DataTable
    ''' <summary>
    ''' Gets all indices by BusinessEntity.
    ''' </summary>
    ''' <param name="BusinessEntity">Title of Business Entity</param>
    ''' <returns>Array with all Indices</returns>
    Private _Logger As Logger
    Private _Database As DatabaseWithFallback

    Public Sub New(LogConfig As LogConfig)
        _Logger = LogConfig.GetLogger
        _Database = New DatabaseWithFallback(LogConfig, My.Application.Service.Client, My.DatabaseECM, My.DatabaseIDB)

        Dim oSQL = $"SELECT * FROM VWIDB_BE_ATTRIBUTE WHERE LANG_ID = {My.Application.User.LanguageId}"
        DTVWIDB_BE_ATTRIBUTE = _Database.GetDatatable("VWIDB_BE_ATTRIBUTE", oSQL, DatabaseType.IDB, $"LANG_ID = {My.Application.User.LanguageId}")
    End Sub

    Public IDBSystemIndices As List(Of String)

    Public Function GetIndicesByBE(ByVal pBusinessEntity As String) As List(Of String)
        Try
            IDBSystemIndices = New List(Of String) From {
                "ObjectID", "IDBCreatedWhen", "IDBCreatedWho", "IDBChangedWhen", "IDBChangedWho"
            }

            Dim oIndexNames As New List(Of String)
            oIndexNames.AddRange(IDBSystemIndices.ToArray)

            For Each oRow As DataRow In DTVWIDB_BE_ATTRIBUTE.Rows
                oIndexNames.Add(oRow.Item("ATTR_TITLE").ToString)
            Next

            oIndexNames.Sort()

            Return oIndexNames
        Catch ex As Exception
            _Logger.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error getting the IDB Indicies")
            Return Nothing
        End Try
    End Function
    Public Function GetTypeOfIndex(ByVal pIndexname As String) As Integer
        Try
            For Each oRow As DataRow In DTVWIDB_BE_ATTRIBUTE.Rows
                If oRow.Item("ATTR_TITLE").ToString = pIndexname Then
                    Return Integer.Parse(oRow.Item("TYP_ID").ToString)
                End If
            Next
        Catch ex As Exception
            _Logger.Error(ex)
            Return Nothing
        End Try
    End Function

    Public Function GetVariableValue(pAttributeName As String, Optional pIDBType As Integer = 0, Optional pFromIDB As Boolean = False) As Object
        Try
            Dim oSingleAttribute As Boolean
            Select Case pIDBType
                Case 8
                    oSingleAttribute = False
                Case 9
                    oSingleAttribute = False
                Case Else
                    oSingleAttribute = True
            End Select

            Dim oAttributeValue As Object = Nothing

            If Not IsNothing(My.Tables.DTIDB_DOC_DATA) Then
                If oSingleAttribute = True And My.Tables.DTIDB_DOC_DATA.Rows.Count = 1 And pFromIDB = False Then
                    Try
                        If pAttributeName = "IDBCreatedWhen" Then
                            pAttributeName = "ADDED_WHEN"
                        ElseIf pAttributeName = "IDBCreatedWho" Then
                            pAttributeName = "ADDED_WHO"
                        ElseIf pAttributeName = "IDBChangedWhen" Then
                            pAttributeName = "CHANGED_WHEN"
                        ElseIf pAttributeName = "IDBChangedWho" Then
                            pAttributeName = "CHANGED_WHO"
                        End If

                        oAttributeValue = My.Tables.DTIDB_DOC_DATA.Rows(0).Item(pAttributeName)
                    Catch ex As Exception
                        _Logger.Debug($"Error getting Attribute from IDB_DT_DOC_DATA: {ex.Message}")
                    End Try

                End If
            End If

            If Not IsNothing(oAttributeValue) Then
                Return oAttributeValue
            Else
                _Logger.Debug($"oAttributeValue for Attribute [{pAttributeName}] is so far nothing..Now trying FNIDB_PM_GET_VARIABLE_VALUE ")
            End If
            Dim oFNSQL = $"SELECT * FROM [dbo].[FNIDB_PM_GET_VARIABLE_VALUE] ({My.Application.Globix.CURRENT_IDB_OBJ_ID},'{pAttributeName}','{My.Application.User.Language}',CONVERT(BIT,'0'))"
            Dim oDatatable As DataTable = My.DatabaseIDB.GetDatatable(oFNSQL)
            If oDatatable.Rows.Count = 1 Then
                oAttributeValue = oDatatable.Rows(0).Item(0)
            End If
            Return oAttributeValue
        Catch ex As Exception
            _Logger.Error(ex)
            Return Nothing
        End Try
    End Function
    Public Function Delete_Term_Object_From_Metadata(pAttributeName As String, pTerm2Delete As String) As Object
        Try
            Dim oIdIsForeign As Integer = 1
            Dim oDELSQL = $"EXEC PRIDB_DELETE_TERM_OBJECT_METADATA {My.Application.Globix.CURRENT_IDB_OBJ_ID},'{pAttributeName}','{pTerm2Delete}','{My.Application.User.UserName}','{My.Application.User.Language}',{oIdIsForeign}"
            My.DatabaseIDB.ExecuteNonQuery(oDELSQL)

        Catch ex As Exception
            _Logger.Error(ex)
            Return Nothing
        End Try
    End Function
    Public Function Delete_AttributeData(pObjectId As Int64, pAttributeName As String) As Object
        Try
            Dim oDELSQL = $"EXEC PRIDB_DELETE_ATTRIBUTE_DATA {pObjectId},'{pAttributeName}','{My.Application.User.UserName}'"
            My.DatabaseIDB.ExecuteNonQuery(oDELSQL)

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

    Public Function SetVariableValue(pAttributeName As String, pNewValue As Object, Optional pCheckDeleted As Boolean = False, Optional oIDBTyp As Integer = 0) As Boolean
        Try
            Dim oType = pNewValue.GetType.ToString
            If oType = "System.Data.DataTable" Then
                Dim oDTMyNewValues As DataTable = pNewValue
                Dim oOldAttributeResult As Object
                Dim oTypeOldResult As Object

                If pCheckDeleted = True Then
                    oOldAttributeResult = GetVariableValue(pAttributeName, oIDBTyp)
                    oTypeOldResult = oOldAttributeResult.GetType.ToString
                    If oTypeOldResult = "System.Data.DataTable" Then
                        Dim oOldValues As DataTable = oOldAttributeResult
                        If oOldValues.Rows.Count > 1 Then

                            'now Checking whether the old row still remains in Vector? If not it will be deleted as it cannot be replaced in multivalues
                            For Each oOldValueRow As DataRow In oOldValues.Rows
                                Dim oExists As Boolean = False
                                For Each oNewValueRow As DataRow In oDTMyNewValues.Rows
                                    Dim oInfo1 = $"Checking oldValue[{oOldValueRow.Item(0)}] vs NewValue [{oNewValueRow.Item(1)}]"
                                    If oNewValueRow.Item(1).ToString.ToUpper = oOldValueRow.Item(0).ToString.ToUpper Then
                                        oExists = True
                                        Exit For
                                    End If
                                Next

                                If oExists = False Then
                                    Dim oInfo = $"Value [{oOldValueRow.Item(0)}] no longer existing in Vector-Attribute [{pAttributeName}] - will be deleted!"
                                    _Logger.Debug(oInfo)
                                    SetVariableValue(My.Application.Globix.CURRENT_PROFILE_LOG_INDEX, oInfo)
                                    Delete_Term_Object_From_Metadata(pAttributeName, oOldValueRow.Item(0))
                                End If

                            Next
                        End If
                    Else
                        If oDTMyNewValues.Rows.Count > 1 Then
                            Dim oExists As Boolean = False
                            For Each oNewValueRow As DataRow In oDTMyNewValues.Rows
                                Dim oInfo1 = $"Checking oldValue[{oOldAttributeResult}] vs NewValue [{oNewValueRow.Item(1)}]"
                                If oNewValueRow.Item(1).ToString.ToUpper = oOldAttributeResult.ToString.ToUpper Then
                                    oExists = True
                                    Exit For
                                End If
                            Next
                            If oExists = False Then
                                Dim oInfo2 = $"Value [{oOldAttributeResult}] no longer existing in Vector-Attribute [{pAttributeName}] - will be deleted!"
                                _Logger.Debug(oInfo2)
                                SetVariableValue(My.Application.Globix.CURRENT_PROFILE_LOG_INDEX, oInfo2)
                                Delete_Term_Object_From_Metadata(pAttributeName, oOldAttributeResult)
                            End If
                        Else
                            Dim oInfo = $"Value [{oOldAttributeResult}] of Attribute [{pAttributeName}] obviously was updated during runtime - will be deleted!"
                            _Logger.Debug(oInfo)
                            SetVariableValue(My.Application.Globix.CURRENT_PROFILE_LOG_INDEX, oInfo)
                            Delete_Term_Object_From_Metadata(pAttributeName, oOldAttributeResult)
                        End If

                    End If

                End If

                For Each oNewValueRow As DataRow In oDTMyNewValues.Rows
                    Dim oSuccess As Boolean = False
                    Dim oFNSQL = $"DECLARE @NEW_OBJ_MD_ID BIGINT " & vbNewLine & $"EXEC PRIDB_NEW_OBJ_DATA {My.Application.Globix.CURRENT_IDB_OBJ_ID},'{pAttributeName}','{My.Application.User.UserName}','{oNewValueRow.Item(1).ToString}','{My.Application.User.Language}',0,@OMD_ID = @NEW_OBJ_MD_ID OUTPUT"
                    oSuccess = My.DatabaseIDB.ExecuteNonQuery(oFNSQL)
                    If oSuccess = False Then
                        Return False
                    End If
                Next
                Return True
            Else
                Dim oFNSQL = $"DECLARE @NEW_OBJ_MD_ID BIGINT " & vbNewLine & $"EXEC PRIDB_NEW_OBJ_DATA {My.Application.Globix.CURRENT_IDB_OBJ_ID},'{pAttributeName}','{My.Application.User.UserName}','{pNewValue}','{My.Application.User.Language}',0,@OMD_ID = @NEW_OBJ_MD_ID OUTPUT"
                Return My.DatabaseIDB.ExecuteNonQuery(oFNSQL)
            End If

        Catch ex As Exception
            _Logger.Error(ex)
            Return False
        End Try
    End Function

End Class
