Imports DevExpress.DataAccess.Native.Json
Imports DigitalData.Modules.EDMI.API.Constants
Imports DigitalData.Modules.EDMI.API.DatabaseWithFallback

Public Class ClassFinalizeDoc
    Public Shared Function Write_Final_Metadata(WMObject As WINDREAMLib.WMObject)
        Try
            Dim _error As Boolean = False
            If CURRENT_DT_FINAL_INDEXING Is Nothing Then
                Dim oSQL = String.Format("select * from  TBPM_PROFILE_FINAL_INDEXING where PROFIL_ID = {0}", CURRENT_ProfilGUID)
                'CURRENT_DT_FINAL_INDEXING = DatabaseFallback.GetDatatableECM(oSQL) ', "Write_Final_Metadata")
                CURRENT_DT_FINAL_INDEXING = DatabaseFallback.GetDatatable("TBPM_PROFILE_FINAL_INDEXING", New GetDatatableOptions(oSQL, DatabaseType.ECM) With {
                    .FilterExpression = $"PROFIL_ID = {CURRENT_ProfilGUID}"
                })

            End If
            If CURRENT_DT_FINAL_INDEXING.Rows.Count > 0 Then

                'Jetzt finale Indexe setzen
                LOGGER.Debug("working final indices for doc: " & WMObject.aName)
                For Each dr As DataRow In CURRENT_DT_FINAL_INDEXING.Rows
                    Dim ovalueString As String = dr.Item("VALUE").ToString
                    Dim INDEXNAME = dr.Item("INDEXNAME").ToString
                    Dim oContinueOnIndifferentState As Boolean = CBool(dr.Item("CONTINUE_INDETERMINED"))
                    Dim VektorBeahaviour = dr.Item("IF_VEKTOR_BEHAVIOUR").ToString
                    If ovalueString.ToUpper = "SQL-Command".ToUpper Then '###### Indexierung mit variablen SQL ###
                        LOGGER.Debug("indexing with dynamic sql...")
                        'Dim SQL_COMMAND = dr.Item("SQL_COMMAND")
                        '' Regulären Ausdruck zum Auslesen der Indexe definieren
                        'Dim preg As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"
                        '' einen Regulären Ausdruck laden
                        'Dim regulärerAusdruck As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(preg)
                        '' die Vorkommen im SQL-String auslesen
                        'Dim elemente As System.Text.RegularExpressions.MatchCollection = regulärerAusdruck.Matches(SQL_COMMAND)
                        ''####
                        '' alle Vorkommen innerhalbd er Namenkonvention durchlaufen
                        'For Each element As System.Text.RegularExpressions.Match In elemente
                        '    Try
                        '        If LogErrorsOnly = False Then LOGGER.Info(" element in RegeX: " & element.Value)
                        '        Dim WDINDEXNAME = element.Value.Substring(2, element.Value.Length - 3)
                        '        Dim wertWD = WMObject.GetVariableValue(WDINDEXNAME)
                        '        If Not IsNothing(wertWD) Then
                        '            SQL_COMMAND = SQL_COMMAND.ToString.Replace(element.Value, wertWD)
                        '        Else
                        '            LOGGER.Info(">>Attention: indexvalue is invalid")
                        '        End If
                        '    Catch ex As Exception
                        '        LOGGER.Info("Unexpected Error in Checking control values for Variable SQL Result - ERROR: " & ex.Message)
                        '    End Try
                        'Next
                        Dim sql_Statement = clsPatterns.ReplaceUserValues(dr.Item("SQL_COMMAND"))
                        sql_Statement = clsPatterns.ReplaceInternalValues(sql_Statement)
                        sql_Statement = clsPatterns.ReplaceWindreamIndicies(sql_Statement, WMObject, True)
                        LOGGER.Debug("sql after ReplaceAllValues: " & sql_Statement)
                        Dim oDynamic_value = DatabaseFallback.GetScalarValueECM(sql_Statement) ', CONNECTION_STRING_ECM, "Write_Final_Metadata/dynamic_value")
                        If Not IsNothing(oDynamic_value) Then
                            ovalueString = oDynamic_value
                        Else
                            Continue For
                        End If
                    Else
                        If ovalueString.StartsWith("v") Then
                            Select Case dr.Item("VALUE").ToString
                                Case "vDate"
                                    ovalueString = Now.ToShortDateString
                                Case "vUserName"
                                    ovalueString = USER_USERNAME
                                Case Else
                                    ovalueString = dr.Item("VALUE")
                            End Select
                        End If
                    End If

                    Dim result() As String
                    ReDim Preserve result(0)
                    result(0) = ovalueString

                    Dim oIndexType = WINDREAM.GetTypeOfIndex(INDEXNAME)
                    LOGGER.Debug($"oIndexType {oIndexType.ToString}")
                    If oIndexType > 4000 And oIndexType < 5000 Then
                        'Hier muss nun separat als Vektorfeld indexiert werden
                        If Indexiere_VektorfeldPM(ovalueString, INDEXNAME, WMObject) = True Then
                            LOGGER.Debug("FINALER INDEX '" & INDEXNAME.Replace("[%VKT", "") & "' WURDE ERFOLGREICH GESETZT")
                        Else

                            MsgBox("Unexpected error in finalindexing vektorvalue - check the log", MsgBoxStyle.Critical)
                            _error = True

                        End If
                    Else
                        LOGGER.Debug("now indexing..")

                        If WINDREAM_MOD.SetFileIndex(CURRENT_DOC_PATH, INDEXNAME, ovalueString, CURRENT_WMObjecttype) = True Then 'Indexiere_File(INDEXNAME, result, WMObject) = True Then
                            LOGGER.Debug("FINALER INDEX '" & INDEXNAME & "' WURDE ERFOLGREICH GESETZT")
                            LOGGER.Debug("")
                            'Nun das Logging
                            If CURRENT_PROFILE_LOG_INDEX <> "" Then
                                Dim logstr = Return_LOGString(ovalueString, "DDFINALINDEX", INDEXNAME)
                                Indexiere_VektorfeldPM(logstr, CURRENT_PROFILE_LOG_INDEX, WMObject)
                            End If

                        Else
                            MsgBox("Unexpected error in final index - check the log", MsgBoxStyle.Critical)
                            _error = True
                        End If
                    End If
                    If _error = True Then
                        Exit For
                    End If
                Next
                If _error = True Then
                    Return False
                Else
                    Return True
                End If
            Else
                Return True
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("unexpected error in Write_Final_Metadata: " & ex.Message.ToString, True)
            Return False
        End Try
    End Function

    Private Shared Function Indexiere_File(pIndexName As String, pIndexValues As Object, WMObject As WINDREAMLib.WMObject) As Boolean
        LOGGER.Debug("### Indexiere_File Begin ###")
        Dim indexierung_erfolgreich As Boolean = False
        Try
            Dim oIndexType As Integer = WINDREAM_MOD.GetIndexType(pIndexName)
            If oIndexType > 4095 Then
                LOGGER.Debug("Es Handelt sich um einen VektorIndex...")
                Dim oExistingItems = WINDREAM_MOD.GetIndexValue(CURRENT_DOC_PATH, pIndexName)

                Dim oListofString As New List(Of String)
                If pIndexValues.Length = 0 Then
                    LOGGER.Debug("oSplitArray.Length = 0")
                    oListofString.Add(pIndexValues(0))
                Else
                    LOGGER.Debug($"pIndexValues.Length is > 0 [{pIndexValues.length}] ...")
                    For Each oStr In pIndexValues
                        LOGGER.Debug("pIndexValues - oString : {0}", oStr)
                        oListofString.Add(oStr)
                    Next
                End If

                If oExistingItems.Count > 0 Then
                    LOGGER.Debug("oOverwrite = False and WMObject already contains [{0}] values in attribute,Values will be concatted", oExistingItems.Count)
                    oListofString = oExistingItems.Concat(oListofString).ToList()
                End If
                oListofString = oListofString.Distinct().ToList()
                indexierung_erfolgreich = WINDREAM_MOD.SetFileIndexLoS(CURRENT_DOC_PATH, pIndexName, oListofString, CURRENT_WMObjecttype)
            Else
                Dim oStringValue As String = pIndexValues(0).ToString
                indexierung_erfolgreich = WINDREAM_MOD.SetFileIndex(CURRENT_DOC_PATH, pIndexName, oStringValue, CURRENT_WMObjecttype)
            End If
            Return indexierung_erfolgreich
        Catch ex As Exception
            LOGGER.Warn("⚠️ Unvorhergesehener Fehler bei Indexiere_File: " & ex.Message.ToString)
            Return False
        End Try

        ' Try
        ''Die Arrays vorbereiten
        'Dim arrIndex() As String = Nothing
        'Dim arrValue() As String = Nothing
        'arrIndex = Nothing
        'arrValue = Nothing
        ''Den Indexnamen übergeben
        'ReDim Preserve arrIndex(0)
        'arrIndex(0) = idxxname
        ''Das Array der Idnexwerte überprüfen
        'If idxvalue Is Nothing = False Then
        '    If idxvalue.Length() > 1 Then
        '        LOGGER.Debug("Indexing Index '" & idxxname & "' with Arrayvalue")
        '        Dim anzahl As Integer = 0
        '        For Each indexvalue As String In idxvalue
        '            ReDim Preserve arrValue(anzahl)
        '            arrValue(anzahl) = indexvalue
        '            anzahl += 1
        '        Next
        '    Else
        '        LOGGER.Debug("Indexing Index '" & idxxname & "' with value '" & idxvalue(0) & "'")
        '        ReDim Preserve arrValue(0)
        '        arrValue(0) = idxvalue(0).ToString
        '    End If
        '    'Dim _windreamPM As New ClassPMWindream
        '    'Jetzt das eigentliche Indexieren der Datei
        'File_indexiert = WINDREAM.RunIndexing(WMObject, arrIndex, arrValue)

        'Return File_indexiert
        ' End If

        'Catch ex As Exception
        '    LOGGER.Info("Unvorhergesehener Fehler bei Indexiere_File: " & ex.Message.ToString, True)
        '    Return Err()
        'End Try
    End Function
    Private Shared Function Indexiere_VektorfeldPM(input As String, NameVectorfield As String, WMObject As WINDREAMLib.WMObject)

        Dim _success As Boolean = True
        Dim Anzahl As Integer = 0
        Dim myInputArr As String()
        'Jeden Wert des Vektorfeldes durchlaufen
        Dim wertWD = WMObject.GetVariableValue(NameVectorfield)
        If wertWD Is Nothing = False Then
            'Es wird gegen ein Vektorfeld nachindexiert
            If wertWD.GetType.ToString.Contains("System.Object") Then
                'es handelt sich um ein Vektorfeld - Zuweisen der Indexwerte des Vektorfeldes zu Array
                For Each obj As Object In wertWD
                    If obj Is Nothing = False Then
                        'Das Array anpassen
                        ReDim Preserve myInputArr(Anzahl)
                        'Den Wert im Array speichern
                        myInputArr(Anzahl) = obj.ToString
                        Anzahl += 1
                    End If
                Next
            End If
            'Das Array anpassen
            ReDim Preserve myInputArr(Anzahl)
            'und den letzten Wert übergeben
            myInputArr(Anzahl) = input
        Else
            'Das Array anpassen
            ReDim Preserve myInputArr(Anzahl)
            'und den letzten Wert übergeben
            myInputArr(Anzahl) = input
        End If

        If myInputArr.Length > 0 Then
            'Jetzt die Datei indexieren
            If Indexiere_File(NameVectorfield, myInputArr, WMObject) = False Then
                _success = False
                'errmessage = "Fehler beim Indexieren Vektorfeld '" & NameVKTIndex & "' - ERROR: " & idxerr_message
            End If
        End If

        Return _success
    End Function
    Private Shared Function Return_PM_VEKTOR(input As String, VKTBezeichner As String)
        Dim PM_String As String
        Try
            Dim Bezeichner As String = VKTBezeichner.Replace("[%VKT", "")
            PM_String = "DD-PM#" & Bezeichner & "#" & input & "#" & USER_USERNAME & "#" & Now.ToString
        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Fehler in Return_PM_VEKTOR: " & ex.Message, True)
            PM_String = "DD-PM ERROR: " & ex.Message
        End Try
        Return PM_String

    End Function
    Private Shared Function Return_LOGString(input As String, old As String, indexname As String)
        Dim PM_String As String
        Try
            If old = "DDFINALINDEX" Then
                PM_String = "DD-PMlog-FINAL" & "#" & indexname & "#" & input & "#" & USER_USERNAME & "#" & Now.ToString
            Else
                PM_String = "DD-PMlog-CHG" & "#" & indexname & "#" & "NEW: '" & input & "' - OLD: '" & old & "'" & "#" & USER_USERNAME & "#" & Now.ToString
            End If

        Catch ex As Exception
            LOGGER.Error(ex)
            LOGGER.Info("Fehler in Return_LOGString: " & ex.Message, True)
            PM_String = "DD-PM ERROR: " & ex.Message
        End Try
        Return PM_String

    End Function
End Class
