Public Class ClassIDBData
    Public 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>
    ''' <remarks></remarks>
    ''' 
    Public Function Init()
        Dim oSQL = $"SELECT * FROM VWIDB_BE_ATTRIBUTE"
        'DTVWIDB_BE_ATTRIBUTE = ClassDatabase.Return_Datatable_CS(oSQL, CONNECTION_STRING_IDB)
        DTVWIDB_BE_ATTRIBUTE = DATABASE_IDB.GetDatatable(oSQL)
        Return True
    End Function

    Public IDBSystemIndices As List(Of String)
    Public Function GetIndicesByBE(ByVal BusinessEntity As String) As String()
        Try
            Dim aNames(4) As String
            aNames(0) = "ObjectID"
            aNames(1) = "IDBCreatedWhen"
            aNames(2) = "IDBCreatedWho"
            aNames(3) = "IDBChangedWhen"
            aNames(4) = "IDBChangedWho"
            IDBSystemIndices = aNames.ToList
            ' Array für Indizes vorbereiten
            Dim aIndexNames(DTVWIDB_BE_ATTRIBUTE.Rows.Count + 4) As String
            Dim oCount As Integer = 0
            aIndexNames(oCount) = "ObjectID"
            oCount += 1
            aIndexNames(oCount) = "IDBCreatedWhen"
            oCount += 1
            aIndexNames(oCount) = "IDBCreatedWho"
            oCount += 1
            aIndexNames(oCount) = "IDBChangedWhen"
            oCount += 1
            aIndexNames(oCount) = "IDBChangedWho"
            For Each oRow As DataRow In DTVWIDB_BE_ATTRIBUTE.Rows
                oCount += 1
                aIndexNames(oCount) = oRow.Item("ATTR_TITLE")

            Next


            ' Indexarray sortiert zurückgeben
            Array.Sort(aIndexNames)
            ' Indexarray zurückgeben
            Return aIndexNames

        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 indexname As String) As Integer
        Try
            For Each oRow As DataRow In DTVWIDB_BE_ATTRIBUTE.Rows
                If oRow.Item("ATTR_TITLE") = indexname Then
                    Dim oType = oRow.Item("TYP_ID")
                    Return oType
                End If
            Next

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

    End Function
    Public Function GetVariableValue(oAttributeName As String, Optional oIDBTyp As Integer = 0, Optional FromIDB As Boolean = False) As Object
        Try
            Dim oSingleAttribute As Boolean = True
            Select Case oIDBTyp
                Case 8
                    oSingleAttribute = False
                Case 9
                    oSingleAttribute = False
            End Select
            Dim oAttributeValue

            If oSingleAttribute = True And IDB_DT_DOC_DATA.Rows.Count = 1 And FromIDB = False Then
                Try
                    If oAttributeName = "IDBCreatedWhen" Then
                        oAttributeName = "ADDED_WHEN"
                    ElseIf oAttributeName = "IDBCreatedWho" Then
                        oAttributeName = "ADDED_WHO"
                    ElseIf oAttributeName = "IDBChangedWhen" Then
                        oAttributeName = "CHANGED_WHEN"
                    ElseIf oAttributeName = "IDBChangedWho" Then
                        oAttributeName = "CHANGED_WHO"
                    End If

                    oAttributeValue = IDB_DT_DOC_DATA.Rows(0).Item(oAttributeName)
                Catch ex As Exception
                    LOGGER.Debug($"Error getting Attribute from IDB_DT_DOC_DATA: {ex.Message}")
                End Try

            End If
            If Not IsNothing(oAttributeValue) Then
                Return oAttributeValue
            Else
                LOGGER.Debug($"oAttributeValue for Attribute [{oAttributeName}] is so far nothing..Now trying FNIDB_PM_GET_VARIABLE_VALUE ")
            End If
            Dim oFNSQL = $"SELECT * FROM [dbo].[FNIDB_PM_GET_VARIABLE_VALUE] ({IDB_DOC_ID},'{oAttributeName}','{USER_LANGUAGE}',CONVERT(BIT,'{IDB_USES_WMFILESTORE}'))"

            'oAttributeValue = ClassDatabase.Return_Datatable_CS(oFNSQL, CONNECTION_STRING_IDB)
            oAttributeValue = DATABASE_IDB.GetDatatable(oFNSQL)

            Dim odt As DataTable = oAttributeValue
            If odt.Rows.Count = 1 Then
                oAttributeValue = odt.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(oAttributeName As String, oTerm2Delete As String) As Object
        Try
            Dim oAttributeValue
            Dim oID_IS_FOREIGN As Integer
            oID_IS_FOREIGN = 0
            If IDB_USES_WMFILESTORE Then
                oID_IS_FOREIGN = 1
            End If
            Dim oDELSQL = $"EXEC PRIDB_DELETE_TERM_OBJECT_METADATA {IDB_DOC_ID},'{oAttributeName}','{oTerm2Delete}','{USER_USERNAME}','{USER_LANGUAGE}',{oID_IS_FOREIGN}"

            'DATABASE_ECM.ExecuteNonQuery_ConStr(oDELSQL, CONNECTION_STRING_IDB)
            DATABASE_IDB.ExecuteNonQuery(oDELSQL)

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

    End Function
    Public Function Delete_AttributeData(pIDB_OBJID As Int64, pAttributeName As String) As Object
        Try
            Dim oDELSQL = $"EXEC PRIDB_DELETE_ATTRIBUTE_DATA {pIDB_OBJID},'{pAttributeName}','{USER_USERNAME}'"

            'DATABASE_ECM.ExecuteNonQuery_ConStr(oDELSQL, CONNECTION_STRING_IDB)
            DATABASE_IDB.ExecuteNonQuery(oDELSQL)

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

    End Function

    Public Function SetVariableValue(oAttributeName As String, oNewValue As Object, Optional CheckDeleted As Boolean = False, Optional oIDBTyp As Integer = 0)
        Try
            Dim omytype = oNewValue.GetType.ToString
            If omytype = "System.Data.DataTable" Then
                Dim oDTMyNewValues As DataTable = oNewValue
                Dim oOldAttributeResult
                Dim oTypeOldResult

                If CheckDeleted = True Then
                    oOldAttributeResult = GetVariableValue(oAttributeName, oIDBTyp)
                    oTypeOldResult = oOldAttributeResult.GetType.ToString
                    If oTypeOldResult = "System.Data.DataTable" Then
                        Dim myOldValues As DataTable = oOldAttributeResult
                        If myOldValues.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 myOldValues.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 [{oAttributeName}] - will be deleted!"
                                    LOGGER.Info(oInfo)
                                    SetVariableValue(IDB_LOG_INDEX, oInfo)
                                    Delete_Term_Object_From_Metadata(oAttributeName, 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 [{oAttributeName}] - will be deleted!"
                                LOGGER.Info(oInfo2)
                                SetVariableValue(IDB_LOG_INDEX, oInfo2)
                                Delete_Term_Object_From_Metadata(oAttributeName, oOldAttributeResult)
                            End If
                        Else
                            Dim oInfo = $"Value [{oOldAttributeResult}] of Attribute [{oAttributeName}] obviously was updated during runtime - will be deleted!"
                            LOGGER.Info(oInfo)
                            SetVariableValue(IDB_LOG_INDEX, oInfo)
                            Delete_Term_Object_From_Metadata(oAttributeName, 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 {IDB_DOC_ID},'{oAttributeName}','{USER_USERNAME}','{oNewValueRow.Item(1)}','{USER_LANGUAGE}',{IDB_DOC_ID},@OMD_ID = @NEW_OBJ_MD_ID OUTPUT"

                    'oSuccess = DATABASE_ECM.ExecuteNonQuery_ConStr(oFNSQL, CONNECTION_STRING_IDB)
                    oSuccess = DATABASE_IDB.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 {IDB_DOC_ID},'{oAttributeName}','{USER_USERNAME}','{oNewValue}','{USER_LANGUAGE}',{IDB_DOC_ID},@OMD_ID = @NEW_OBJ_MD_ID OUTPUT"

                'Return DATABASE_ECM.ExecuteNonQuery_ConStr(oFNSQL, CONNECTION_STRING_IDB)
                Return DATABASE_IDB.ExecuteNonQuery(oFNSQL)
            End If

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