Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Text.RegularExpressions
Imports DigitalData.Modules.Logging
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports WINDREAMLib

Public Class clsDateiverarbeitung
    Dim Logger As Logger
    Private MyLoggerConf As LogConfig

#Region "***** Variablen und Konstanten*****"
    Dim _windream As clsWindream_allgemein
    Dim _database As clsDatabase

    Public Shared pr_DTPROFIL_REGELN As DataTable
    Public Shared CURRFile_Exportresult As String

    Public Shared CriticalError As Boolean = False

    Private Shared regel_TYP, regel_INDEX_NAME, regel_QUELLE1, regel_FROM1, regel_FROM2 As String
    Private Shared Indexe() As String = Nothing  ' zum Speichern der Indexe
    Private Shared NI_Values() As String = Nothing  ' zum Speichern der Werte

    Private Shared WD_aktivesDokument As WMObject


    Const WMObjectStreamOpenModeReadWrite = 2
    Const WMObjectEditModeFileSystem = &H15
#End Region
    Public Sub New(MyLogger As LogConfig)
        MyLoggerConf = MyLogger
        Logger = MyLogger.GetLogger()
        _windream = New clsWindream_allgemein(MyLogger)
        _database = New clsDatabase(MyLogger)
    End Sub
    Public Function InitProfilData()
        Try
            pr_DTPROFIL_REGELN = Nothing
            ' Profildaten der Klasse mitteilen
            Logger.Debug("InitProfilData Profildaten zugewiesen....")
            Return True
        Catch ex As Exception
            Logger.Error(ex)
            'clsLogger.AddError(ex.Message, "cls_DV.InitProfilData")
            Return False
        End Try
    End Function
    Public Function Check_File_job(WMdok As WMObject, FileJobType As String, String1 As String, String2 As String, WMObjekttyp As String, windream_index As clsWindream_Index)
        Try
            Select Case FileJobType.ToLower
                Case "Set Index".ToLower
                    Try
                        'Überprüfen ob Value bereits gesetzt wurde?
                        Dim oidxName As String = String1
                        Dim oidxvalue As String = String2
                        If oidxvalue.Contains("[%DATETIME]") Then
                            oidxvalue = oidxvalue.Replace("[%DATETIME]", Now.ToString)
                        End If
                        oidxvalue = REGEX_REPLACE(WMdok, oidxvalue)
                        Logger.Debug($"Index '{oidxName}' shall be set with value '{oidxvalue}'")
                        Dim oarrIndex() As String
                        ReDim Preserve oarrIndex(0)
                        oarrIndex(0) = oidxName
                        Logger.Debug("...nach arrIndex")

                        Dim oArrValue() As String

                        Dim oAktvalue As Object
                        oAktvalue = WMdok.GetVariableValue(oidxName)
                        Logger.Debug("...nach aktValue zuweisen..")
                        Dim oWmtype = clsWindream_allgemein.GetTypeOfIndexAsIntByName(oidxName)
                        Dim oIsVektor As Boolean = False
                        Select Case oWmtype
                            Case 4097
                                oIsVektor = True
                            Case 4098
                                oIsVektor = True
                            Case 4099
                                oIsVektor = True
                            Case 4101
                                oIsVektor = True
                            Case 4103
                                oIsVektor = True
                            Case 4107
                                oIsVektor = True
                            Case 36865
                                oIsVektor = True
                        End Select
                        If oIsVektor = False Then
                            ReDim Preserve oArrValue(0)
                            oArrValue(0) = oidxvalue
                        Else
                            Dim oMyArray()
                            ReDim oMyArray(0)
                            oMyArray(0) = oidxvalue

                            Dim oVektorArray()
                            oVektorArray = Return_VektorArray(WMdok, oidxName, oMyArray, True)
                            If oVektorArray Is Nothing = False Then
                                ReDim oArrValue(oVektorArray.Length - 1)
                                Array.Copy(oVektorArray, oArrValue, oVektorArray.Length)
                            End If
                        End If


                        If oArrValue Is Nothing = False Then

                            windream_index.RunIndexing(WMdok, oarrIndex, oArrValue, WMObjekttyp)
                        Else
                            Logger.Warn("arrValue is nothing - keine Indexierung")
                        End If

                    Catch ex As Exception
                        Logger.Error(ex)
                        'clsLogger.AddError("Unvorhergesehener Fehler: " & ex.Message, "clsProfil.Profil_Durchlauf(SetIndex)")
                    End Try
            End Select
        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try
    End Function
    Private Function CleanInput(strIn As String) As String
        ' Replace invalid characters with empty strings.
        Try
            Return Regex.Replace(strIn, "[^\w\.@-]", "")
            ' If we timeout when replacing invalid characters, 
            ' we should return String.Empty.
        Catch ex As Exception
            Logger.Error(ex)
            Return String.Empty
        End Try
    End Function
    Public Function Export_WMFile2HDD(pWMObject As WMObject, pExportPath As String, Optional pFilename As String = "") As Boolean
        Try
            Dim oWMObject As IWMObject6 = DirectCast(pWMObject, IWMObject6)

            Dim oFilenameWM As String = oWMObject.aName
            Dim oFilenameExport As String
            Dim oSplitIndex
            If pFilename = String.Empty Then
                oSplitIndex = oFilenameWM.LastIndexOf(".")
            Else
                oSplitIndex = pFilename.LastIndexOf(".")
            End If

            Dim oVersion = 1
            Dim oFilename As String
            If pFilename <> String.Empty Then
                oFilename = pFilename.Substring(0, oSplitIndex)
            Else
                oFilename = oFilenameWM.Substring(0, oSplitIndex)
            End If

            oFilename = oFilename.Replace("/", "_")
            Logger.Debug("Preparing export of WMFile {0}..", oFilenameWM)
            Logger.Debug("Filename: {0}", oFilename)
            Logger.Debug("Extension: {0}", clsCURRENT.FILE_Extension)
            Logger.Debug("pExportPath: {0}", pExportPath)

            ' build the file path in case the exported file doesn't already exist
            oFilenameExport = BuildExportPath(pExportPath, oFilename, clsCURRENT.FILE_Extension)

            ' Add version until we find the version that does NOT exist
            Do While File.Exists(oFilenameExport)
                oVersion += 1
                oFilenameExport = BuildExportPath(pExportPath, oFilename, clsCURRENT.FILE_Extension, oVersion)
            Loop

            Logger.Debug("File will be exported to {0}", oFilenameExport)

            Logger.Debug("Opening file stream..")
            Dim oStream As WMStream = oWMObject.OpenStream("BinaryObject", WMObjectStreamOpenMode.WMObjectStreamOpenModeRead)
            Dim oWMFileIO As New WMOTOOLLib.WMFileIO() With {
                .aWMStream = oStream,
                .bstrOriginalFileName = oFilenameExport
            }

            Logger.Debug("Exporting file..")
            oWMFileIO.ExportOriginal(True)

            Logger.Debug("Cleaning up..")
            oStream.Close()
            oStream = Nothing
            oWMFileIO = Nothing
            Logger.Debug("File exported!")

            If File.Exists(oFilenameExport) Then
                Logger.Info($"File Export to HDD [{oFilenameExport}] was successfull!")
                CURRFile_Exportresult = oFilenameExport
                clsCURRENT.EXPORTED_FILENAME = oFilenameExport
                clsCURRENT.TEMP_FILES.Add(oFilenameExport)
                Logger.Debug("FileInfo Added to variables...")
                Return True
            Else
                Logger.Warn($"Export not successfull or File.Exists = false Export: [{oFilenameExport}]")
                Return False
            End If

            Return True
        Catch ex As Exception
            Logger.Error(ex)
            Logger.Info($"Unexpected error in Export_WMFile2HDD [{ex.Message}]")
            Return False
        End Try
    End Function
    Public Function Archive_Document(pWMObject As WMObject, pDateOperator As String, pIntervall As Integer, pFromDate As String) As Boolean
        Dim oDateFrom As Date
        Try
            Const WMObjectEditModeLifeCycleEdit = "&H00000080"
            Const WMLifeCycleTypeArchivePeriod = 2
            Logger.Debug($"ArchiveDate for WMFile shall be changed: pFromDate [{pFromDate}] pDateOperator [{pDateOperator}]...")
            pWMObject.LockFor(WMObjectEditModeLifeCycleEdit)
            Dim oLC = pWMObject.aWMLifeCycle()

            If pFromDate = "Now" Then
                oDateFrom = Now
            Else
                oDateFrom = CDate(pFromDate)
            End If
            Dim oDateIntervall As DateInterval
            Select Case pDateOperator
                Case "y"
                    oDateIntervall = DateInterval.Year
                Case "m"
                    oDateIntervall = DateInterval.Month
                Case "d"
                    oDateIntervall = DateInterval.Day
                Case Else
                    Logger.Warn($"ATTENTION: Following DateOperator [{pDateOperator}] is not integrated! ")
                    If pWMObject.aLocked Then
                        pWMObject.unlock()
                    End If
                    Return False
            End Select
            Dim archBis = DateAdd(oDateIntervall, pIntervall, oDateFrom)
            Logger.Debug($"...archBis is [{archBis.ToShortDateString}]!")
            'Dim pArchiveDate As String = archBis.ToString("yyyy-MM-dd")
            oLC.SetPeriodEndDate(WMLifeCycleTypeArchivePeriod, archBis)

            pWMObject.Save()
            If pWMObject.aLocked Then
                pWMObject.unlock()
            End If
            Logger.Info($"Archive-Date of file [{pWMObject.aName}] was changed successfully!")
            Return True
        Catch ex As Exception
            Try
                If pWMObject.aLocked Then
                    pWMObject.unlock()
                End If
            Catch ex1 As Exception

            End Try

            Logger.Error(ex)
            Logger.Info($"Unexpected error in Archive_Document [{ex.Message}]")
            Logger.Info($"oDateFrom so far is [{oDateFrom.ToString}]")
            Return False
        End Try
    End Function
    Private Function BuildExportPath(BasePath As String, FilenameWithoutExtension As String, Extension As String, Optional Version As Integer = 1)
        Dim oFilename

        If Version = 1 Then
            oFilename = FilenameWithoutExtension & Extension
        Else
            oFilename = FilenameWithoutExtension & "_" & Version & Extension
        End If

        Return Path.Combine(BasePath, oFilename)
    End Function



    Public Function Rename_File(WMFile As WMObject, konvention As String)
        Try
            Logger.Debug("Konvention: '" & konvention & "'")

            'Regulären Ausdruck zum Auslesen der windream-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 reg_elemente As System.Text.RegularExpressions.MatchCollection = regulärerAusdruck.Matches(konvention)
            Dim i As Integer = 0
            ' alle Vorkommen der windream-Indexe im SQL-String durchlaufen
            For Each reg_element As System.Text.RegularExpressions.Match In reg_elemente
                'die Zeichen [% und ] entfernen (liefert den wirklichen windream-Index)
                Dim reg_element_Ohne_SZ As String = reg_element.Value.Replace("[%", "")
                reg_element_Ohne_SZ = reg_element_Ohne_SZ.Replace("]", "")
                Logger.Debug("Indexwert aus Index '" & reg_element_Ohne_SZ & "' auslesen....")
                Dim wdIndexwert
                'den Wert des Indexes für das aktuelle Dokument auslesen
                wdIndexwert = WMFile.GetVariableValue(reg_element_Ohne_SZ)
                If wdIndexwert Is Nothing = False Then
                    If Not wdIndexwert.GetType.ToString.Contains("System.Object") Then
                        Logger.Debug("Namenkonvention (" & i & ") " & konvention)
                        wdIndexwert = wdIndexwert.ToString.TrimEnd
                        wdIndexwert = wdIndexwert.ToString.TrimStart
                        Logger.Debug("Ausgelesener Indexwert = '" & wdIndexwert & "'")
                        konvention = konvention.Replace(reg_element.Value, wdIndexwert.ToString)
                        i += 1
                    Else
                        Logger.Warn("Achtung gelesener Wert ist ein Vektorfeld - keine Umbenennung möglich ")
                    End If
                End If
            Next
            Dim version As Integer = 2
            Dim ZielPfad As String = Path.GetDirectoryName(CURRFile_Exportresult)
            Logger.Debug("ZielPfad: " & ZielPfad)
            Dim Filename = konvention
            Dim Extension = Path.GetExtension(CURRFile_Exportresult)
            Logger.Debug("Extension: " & Extension)
            Dim tempFilename As String = ZielPfad & "\" & Filename & Extension
            Logger.Debug("tempFilename: " & tempFilename)
            'Überprüfen ob File existiert
            Do While IO.File.Exists(tempFilename) = True
                tempFilename = ZielPfad & "\" & Filename & "_" & version & Extension
                version += 1
            Loop
            Logger.Debug("RenameFile - OLDFilename: " & CURRFile_Exportresult)
            Logger.Debug("NEWFilename: " & Path.GetFileName(tempFilename))
            Threading.Thread.Sleep(500)
            Try
                My.Computer.FileSystem.RenameFile(CURRFile_Exportresult, Path.GetFileName(tempFilename))
            Catch ex As Exception
                If ex.Message.Contains("The process cannot access the file") Then
                    tempFilename = tempFilename.Replace(".pdf", "_X.pdf")
                    My.Computer.FileSystem.CopyFile(CURRFile_Exportresult, tempFilename)
                    Logger.Info("File is in use - NewName " & tempFilename)
                    CURRFile_Exportresult = tempFilename
                End If
            End Try

            Logger.Info("Datei wurde erfolgreich umbenannt.")
            Return True
        Catch ex As Exception
            Logger.Error(ex)

            Return False
        End Try
    End Function


    Public Function Rename_File_Vektor(WMFile As WMObject, WMINDEX_NAME As String)
        Try
            Dim WMIndexwert
            Dim ZielPfad As String = Path.GetDirectoryName(CURRFile_Exportresult)
            Logger.Debug("ZielPfad: " & ZielPfad)
            Dim Extension = Path.GetExtension(CURRFile_Exportresult)
            Logger.Debug("Extension: " & Extension)

            If WMINDEX_NAME.StartsWith("[%") Then
                WMINDEX_NAME = WMINDEX_NAME.Replace("[%", "")
                WMINDEX_NAME = WMINDEX_NAME.Replace("]", "")
            End If
            'den Wert des Indexes für das aktuelle Dokument auslesen
            WMIndexwert = WMFile.GetVariableValue(WMINDEX_NAME)
            If WMIndexwert.GetType.ToString.Contains("System.Object") Then
                Logger.Debug("Rename_File_Vektor in Progress for index " & WMINDEX_NAME)
                Dim anz As Integer = 1
                Dim copybasefile As String
                For Each WMvalue As Object In WMIndexwert
                    'Für jeden Value eine Datei erzeugen
                    Try
                        If WMvalue.ToString <> String.Empty Then
                            Dim tempFilename As String = ZielPfad & "\" & WMvalue & Extension
                            Logger.Debug("tempFilename: " & tempFilename)
                            If anz = 1 Then
                                Logger.Debug("RenameFile - OLDFilename: " & CURRFile_Exportresult & " - NEWFilename: " & Path.GetFileName(tempFilename))
                                My.Computer.FileSystem.RenameFile(CURRFile_Exportresult, Path.GetFileName(tempFilename))
                                copybasefile = tempFilename
                            Else
                                Dim version As Integer = 2
                                'Überprüfen ob File existiert
                                Do While IO.File.Exists(tempFilename) = True
                                    tempFilename = ZielPfad & "\" & WMvalue & "_" & version & Extension
                                    version += 1
                                Loop
                                File.Copy(copybasefile, tempFilename, True)
                            End If
                            anz += 1

                        End If
                    Catch ex As Exception
                        Logger.Error(ex)
                        '
                    End Try
                Next
            Else
                Logger.Warn("Achtung WMIndex " & WMINDEX_NAME & " scheint kein Vektorfeld zu sein!")
                Return False
            End If

            Logger.Info("Dateien wurde erfolgreich nach Vektorfeld erzeugt.")
            Return True
        Catch ex As Exception
            Logger.Error(ex)

        End Try
    End Function

    Private Function GetWMAPILink(docId As String, userId As String)
        Dim hostname = "http://documents.mylogitservices.syncreon.com:8100"
        Dim link As String = $"{hostname}/WMWebApi/windream.web.api/DigitalData/BNSDownload?docId={docId}&userId={userId}"

        Return link
    End Function

    Private Function GetDocTypeCategory(docType As String)
        Select Case docType
            Case "Abliefernachweis"
                Return 5
            Case "Begleitdokument"
                Return 6
            Case Else
                Return 0
        End Select
    End Function

    ''' <summary>
    ''' Generiert einen Link für BNS und fügt das Dokument WMFile 
    ''' ins BNS ein
    ''' </summary>
    ''' <param name="WMFile">Das WMObject, dass das aktuelle Dokument repräsentiert</param>
    ''' <param name="userId">Die eindeutige Benutzer Kennung für die Authentifizierung in Windream</param>
    Public Function BNSjsonDownload(WMFile As WMObject, userId As String, apiAddress As String)
        Dim url As String
        Try
            Logger.Info("handling BNSjsonDownload.....")
            ' Indizes für das aktuelle Dokument auslesen
            Dim SENDUNGNR = WMFile.GetVariableValue("Sendungnr")
            Dim DOKID = WMFile.GetVariableValue("Dokument-ID")
            Dim DOKART = WMFile.GetVariableValue("Dokumentart")
            Dim now As DateTime = DateTime.Now

            ' Download Link für Dokument erstellen
            Dim link As String = GetWMAPILink(DOKID, userId)

            ' JSON Payload erstellen und serialisieren
            Dim doc As New BNSDocument(MyLoggerConf)
            doc.Bemerkung = DOKART
            'Dokumente sollen unbegrenzt gültig sein
            'doc.Ivalidfrom = now
            'doc.Ivaliduntil = now.AddDays(30)
            doc.Pfad = link
            doc.Dateiname = WMFile.aName
            doc.Kategorien = New List(Of BNSDocumentCategory) From {
                New BNSDocumentCategory With {.Id = GetDocTypeCategory(DOKART)}
            }

            Dim json As String = JsonConvert.SerializeObject(doc, Formatting.Indented)
            Dim bytes As Byte() = Encoding.Default.GetBytes(json)

            ' HTTP Request machen 
            ' Mandanten ID ist Standartmäßig 1
            Dim mandatenId As Integer = 1
            ' Für Tests auf Sendung gesetzt, später sollte dieser String konfigurierbar sein
            Dim geschaeftsObjekt = "Sendung"
            ' Für Tests wird hier die Sendungsnummer verwendet, später hängt der verwendete Index von 'geschaeftsObjekt' ab
            Dim geschaeftsId = SENDUNGNR
            url = $"https://{apiAddress}/onwebui/api/Customer/{mandatenId}/{geschaeftsObjekt}/{geschaeftsId}/dokument"

            ' Logger.Debug($">> Generiertes JSON: {json}")
            Logger.Debug($">> Creating WebRequest for {url}")
            Dim req As HttpWebRequest
            Try
                req = WebRequest.Create(url)
            Catch ex As Exception
                Logger.Warn($"Unhandled Exception in BNSjsonDownload - CreatingWebRequest ({url}) - Profile ({clsCURRENT._Profilname}) {ex.Message}")
                Logger.Error(ex)
                Return False
            End Try


            req.Method = "POST"
            req.ContentType = "application/json"
            req.ContentLength = bytes.Length
            req.Timeout = 3000
            req.ServicePoint.Expect100Continue = False
            Dim reqStream As Stream
            Try
                reqStream = req.GetRequestStream()
            Catch ex As Exception
                Logger.Warn($"Unhandled Exception in BNSjsonDownload - GetRequestStream ({url}) - Profile ({clsCURRENT._Profilname}) {ex.Message}")
                Logger.Error(ex)
                Return False
            End Try

            reqStream.Write(bytes, 0, bytes.Length)
            reqStream.Close()

            'Logger.Debug($">> Datei wird hochgeladen... docId: {DOKID}, dokart: {DOKART}, userId: {userId}")
            'Logger.Debug($">> Upload URL: {url}")
            Try
                Using res As HttpWebResponse = req.GetResponse()
                    Dim code As HttpStatusCode = res.StatusCode
                    Dim text As String = res.StatusDescription

                    ' Status 201 Created bedeutet: Alles okay!
                    If code = HttpStatusCode.Created Then
                        Logger.Info($"File has been uploaded: docId: {DOKID}, dokart: {DOKART}, userId: {userId}")
                    Else
                        Logger.Warn($"Server Error (HTTP {code}: {text})")
                    End If
                End Using
            Catch ex As Exception
                Logger.Warn($"Unhandled Exception in BNSjsonDownload - GetResponse ({url}) - Profile ({clsCURRENT._Profilname}) {ex.Message}")
                Logger.Error(ex)
                Return False
            End Try

            Return True
        Catch ex As Exception
            Logger.Warn($"Unhandled Exception in BNSjsonDownload - Url ({url}) - Profile ({clsCURRENT._Profilname}) {ex.Message}")
            Logger.Error(ex)
            Return False
        End Try
    End Function
    Public Function RUN_ORACLE_COMMAND(WMFile As WMObject, OracleCS As String, OracleCommandRAW As String)
        Try
            Dim result = REGEX_REPLACE(WMFile, OracleCommandRAW)
            If result = Nothing Then
                Return False
            ElseIf result.ToString.Contains("[%") Then
                Logger.Warn($"Replace Function OracleCommandRAW did not match all patterns: {result.ToString}")
                Return False
            End If

            Logger.Warn($"Executing Oracle Command is no longer implemented")
            Return False

        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try
    End Function
    Public Function RUN_MSSQL_COMMAND(WMFile As WMObject, MSSQLCS As String, SQLCommandRAW As String)
        Try
            Dim result = REGEX_REPLACE(WMFile, SQLCommandRAW)
            If result = Nothing Then
                Return False
            ElseIf result.ToString.Contains("[%") Then
                Logger.Warn($"Replace Function SQLCommandRAW did not match all patterns: {result.ToString}")
                Return False
            End If


            If _database.ExecuteonMSSQL(MSSQLCS, result) = True Then
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            Logger.Error(ex)

            Return False
        End Try
    End Function
    Private Function Return_VektorArray(ByVal oDocument As WMObject, vktIndexName As String, NIIndexe As Object, CheckDuplikat As Boolean)
        Try
            Dim missing As Boolean = False
            Dim Anzahl As Integer = 0
            Dim ValueArray()
            'Jeden Wert des Vektorfeldes durchlaufen
            Dim wertWD = oDocument.GetVariableValue(vktIndexName)
            If wertWD Is Nothing = False Then
                'Nochmals prüfen ob wirklich Array
                If wertWD.GetType.ToString.Contains("System.Object") Then
                    'Keine Duplikatprüfung also einfach neues Array füllen
                    If CheckDuplikat = False Then
                        For Each value As Object In wertWD
                            'Das Array anpassen
                            ReDim Preserve ValueArray(Anzahl)
                            'Den Wert im Array speichern
                            ValueArray(Anzahl) = value.ToString
                            Anzahl += 1
                        Next
                        'Und jetzt den/die Neuen Wert(e) anfügen
                        For Each NewValue As Object In NIIndexe
                            If NewValue Is Nothing = False Then
                                'Das Array anpassen
                                ReDim Preserve ValueArray(Anzahl)
                                'Den Wert im Array speichern
                                ValueArray(Anzahl) = NewValue.ToString
                                Anzahl += 1

                            End If
                        Next
                    Else
                        Logger.Debug("Duplikatprüfung soll durchgeführt werden.")
                        'Duplikat Prüfung an, also nur anhängen wenn Wert <>
                        For Each WDValue As Object In wertWD
                            If WDValue Is Nothing = False Then
                                'Erst einmal die ALten Werte schreiben
                                ReDim Preserve ValueArray(Anzahl)
                                'Den Wert im Array speichern
                                ValueArray(Anzahl) = WDValue.ToString
                                Logger.Debug("Value (" & Anzahl & ") " & WDValue.ToString)
                                Anzahl += 1
                            End If
                        Next
                        'Jetzt die Neuen Werte auf Duplikate überprüfen
                        For Each NewValue As Object In NIIndexe
                            If NewValue Is Nothing = False Then
                                If ValueArray.Contains(NewValue) = False Then
                                    Logger.Debug("New Value (" & Anzahl & ") " & NewValue.ToString)
                                    'Das Array anpassen
                                    ReDim Preserve ValueArray(Anzahl)
                                    'Den Wert im Array speichern
                                    ValueArray(Anzahl) = NewValue.ToString
                                    Anzahl += 1
                                Else
                                    Logger.Debug("Value '" & NewValue.ToString & "' bereits in Vektorfeld enthalten")
                                End If
                            End If
                        Next
                    End If
                End If
            Else
                Logger.Debug("Vektorfeld ist noch leer....")
                'Den/die Neuen Wert(e) anfügen
                For Each NewValue As Object In NIIndexe
                    If NewValue Is Nothing = False Then
                        If CheckDuplikat = True Then
                            If ValueArray Is Nothing = False Then
                                If ValueArray.Contains(NewValue) = False Then
                                    'Das Array anpassen
                                    ReDim Preserve ValueArray(Anzahl)
                                    'Den Wert im Array speichern
                                    ValueArray(Anzahl) = NewValue.ToString
                                    Anzahl += 1
                                Else
                                    Logger.Debug("Value '" & NewValue.ToString & "' bereits in Array enthalten")
                                End If
                            Else 'Dererste Wert, also hinzufügen
                                'Das Array anpassen
                                ReDim Preserve ValueArray(Anzahl)
                                'Den Wert im Array speichern
                                ValueArray(Anzahl) = NewValue.ToString
                                Anzahl += 1

                            End If

                        Else
                            'Das Array anpassen
                            ReDim Preserve ValueArray(Anzahl)
                            'Den Wert im Array speichern
                            ValueArray(Anzahl) = NewValue.ToString
                            Anzahl += 1
                        End If
                    End If
                Next
            End If

            Logger.Debug("Return ValueArray: length " & ValueArray.Length)
            Return ValueArray
        Catch ex As Exception
            Logger.Error(ex)
            Return Nothing
        End Try
    End Function
    Public Function REGEX_REPLACE(WMFile As WMObject, _STRING As String)
        Try
            Logger.Debug("REGEX_REPLACE before replacing: '" & _STRING & "'")
            ' Regulären Ausdruck zum Auslesen der windream-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 reg_elemente As System.Text.RegularExpressions.MatchCollection = regulärerAusdruck.Matches(_STRING)
            Dim i As Integer = 0
            ' alle Vorkommen der windream-Indexe im SQL-String durchlaufen
            For Each reg_element As System.Text.RegularExpressions.Match In reg_elemente
                ' die Zeichen [% und ] entfernen (liefert den wirklichen windream-Index)
                Dim reg_element_Ohne_SZ As String = reg_element.Value.Replace("[%", "")
                reg_element_Ohne_SZ = reg_element_Ohne_SZ.Replace("]", "")
                Logger.Debug("read indexvalue from index '" & reg_element_Ohne_SZ & "'....")
                If reg_element_Ohne_SZ = "EXPORTED_FILENAME" Then
                    If clsCURRENT.EXPORTED_FILENAME <> "" Then
                        _STRING = _STRING.Replace(reg_element.Value, clsCURRENT.EXPORTED_FILENAME)
                    End If
                ElseIf reg_element_Ohne_SZ = "ENV_USERNAME" Then
                    _STRING = _STRING.Replace(reg_element.Value, Environment.UserName)
                Else
                    Dim wdIndexwert
                    ' den Wert des Indexes für das aktuelle Dokument auslesen
                    wdIndexwert = WMFile.GetVariableValue(reg_element_Ohne_SZ)
                    If wdIndexwert Is Nothing = False Then
                        If Not wdIndexwert.GetType.ToString.Contains("System.Object") Then
                            wdIndexwert = wdIndexwert.ToString.TrimEnd
                            wdIndexwert = wdIndexwert.ToString.TrimStart
                            Logger.Debug("indexvalue read is: '" & wdIndexwert & "'")
                            Try
                                Dim oConvertDT As DateTime
                                If DateTime.TryParse(wdIndexwert.ToString, oConvertDT) Then
                                    Logger.Debug("indexvalue is datetime - converting to date")
                                    Dim myDate As Date = wdIndexwert
                                    wdIndexwert = Format(myDate, "yyyy-MM-dd")
                                End If
                            Catch ex As Exception
                                Logger.Warn("clsDateiverarbeitung: Error checking datetime: " & ex.Message)
                            End Try


                            _STRING = _STRING.Replace(reg_element.Value, wdIndexwert.ToString)
                            Logger.Debug("REGEX_String  (" & i & ") " & _STRING)
                            i += 1
                        Else
                            Logger.Warn("Attention: WMIndex is an vectorfield - seperation of values via ;")
                            Logger.Debug("wdIndexValue is System.Object....")
                            Logger.Debug("trying to seperate via ,....")
                            Dim vector_result As String = ""
                            For Each WMvalue As Object In wdIndexwert
                                Dim x As Integer = 0
                                If WMvalue.ToString <> String.Empty Then
                                    WMvalue = WMvalue.ToString.TrimEnd
                                    WMvalue = WMvalue.ToString.TrimStart
                                    If vector_result = "" Then
                                        vector_result = WMvalue
                                    Else
                                        vector_result = vector_result & ";" & WMvalue
                                    End If
                                    x += 1
                                End If
                            Next
                            _STRING = _STRING.Replace(reg_element.Value, vector_result.ToString)
                            Logger.Debug("REGEX_String after vector-for-each  (" & i & ") " & _STRING)
                        End If
                    Else
                        Logger.Info($"Attention: Indexvalue for Index [{reg_element_Ohne_SZ}]is NOTHING, standardvalue '0' will be used - clsDateiverarbeitung.REGEX_REPLACE")
                        _STRING = _STRING.Replace(reg_element.Value, "0")
                    End If
                End If
            Next
            Logger.Debug("REGEX_REPLACE AFTER replacing: '" & _STRING & "'")
            Return _STRING
        Catch ex As Exception
            Logger.Error(ex)

            Return Nothing
        End Try
    End Function

    Public Class BNSDocument
        Dim Logger As Logger
        Public Doksourcetype As Integer = 3
        Public Pfad As String
        'Dokumente sollen unbegrenzt gültig sein
        'Public Ivalidfrom As DateTime
        'Public Ivaliduntil As DateTime
        Public Bemerkung As String
        Public Primaer As Boolean = False
        Public Fremsysid As Integer = 1
        Public Kategorien As List(Of BNSDocumentCategory)
        Public Dateiname As String
        Public Sub New(MyLogger As LogConfig)
            Logger = MyLogger.GetLogger()
        End Sub
    End Class
    Public Class BNSDocumentCategory
        Public Id As Integer
    End Class

End Class

