Imports System.IO

Public Class ClassImport_Windream
    Public Shared Function Import_File(QuellDatei_Path As String, DOCTYPE_ID As Integer)
        Try
            Dim err As Boolean = False
            CURRENT_FILENAME = QuellDatei_Path
            Dim DT_DOCTYPE As DataTable = ClassDatabase.Return_Datatable("SELECT * FROM TBDD_DOKUMENTART WHERE GUID = " & DOCTYPE_ID)
            If Not IsNothing(DT_DOCTYPE) Then
                Dim Targetpath As String = DT_DOCTYPE.Rows(0).Item("ZIEL_PFAD")
                Dim Dokart As String = DT_DOCTYPE.Rows(0).Item("BEZEICHNUNG")
                ClassWindream._WDObjekttyp = DT_DOCTYPE.Rows(0).Item("OBJEKTTYP")

                'Den Namen der Dokumentart generieren
                If ClassImport_Windream.Name_Generieren(DOCTYPE_ID) = False Then
                    err = True
                    Return False
                End If

                'Die Datei nach windream importieren
                Dim streamresult = ClassWindream.Stream_File(QuellDatei_Path, Targetpath)
                If streamresult = True Then
                    Dim sql = "SELECT * FROM TBDD_INDEX_AUTOM WHERE DOCTYPE_ID = " & DOCTYPE_ID
                    Dim dt As DataTable = ClassDatabase.Return_Datatable(sql)
                    Dim indexierung_erfolgreich As Boolean = False
                    If dt Is Nothing = False Then
                        If dt.Rows.Count > 0 Then
                            Dim Count As Integer = 0
                            For Each row As DataRow In dt.Rows
                                Dim indexname = row.Item("INDEXNAME").ToString
                                Dim idxvalue = row.Item("VALUE")
                                If idxvalue.ToString.StartsWith("@") Then
                                    Select Case idxvalue.ToString.ToUpper
                                        Case "@RECORD-ID"
                                            idxvalue = idxvalue.ToString.Replace("@Record-ID", CURRENT_RECORD_ID)
                                        Case "@DOKART"
                                            idxvalue = idxvalue.ToString.Replace("@Dokart", Dokart)
                                    End Select
                                End If
                                If LogErrorsOnly = False Then ClassLogger.Add(">> Indexvalue: " & idxvalue.ToString, False)
                                Count += 1
                                indexierung_erfolgreich = ClassWindream.DateiIndexieren(CURRENT_FILEIN_WD, indexname, idxvalue)
                                If indexierung_erfolgreich = False Then
                                    MsgBox("Unexpected Error in indexing file - See log", MsgBoxStyle.Critical)
                                    err = True
                                    Exit For
                                End If
                                'ByVal WD_File As String, ByVal _Indexname As String, ByVal _Value As String
                            Next
                            If err = True Then
                                Return False
                            End If
                            'den Entity-Key auslesen
                            sql = "Select Top 1 * from TBPMO_WD_OBJECTTYPE where Upper(object_type) = Upper('" & ClassWindream._WDObjekttyp & "')"
                            dt = ClassDatabase.Return_Datatable(sql)
                            If Not dt Is Nothing Then
                                If dt.Rows.Count = 1 Then
                                    Dim indexname = dt.Rows(0).Item("IDXNAME_ENTITYID").ToString
                                    Dim idxvalue = CURRENT_FORM_ID
                                    If LogErrorsOnly = False Then ClassLogger.Add(">> Entity-ID: " & idxvalue.ToString, False)
                                    indexierung_erfolgreich = ClassWindream.DateiIndexieren(CURRENT_FILEIN_WD, indexname, idxvalue)
                                    If indexierung_erfolgreich = False Then
                                        err = True
                                        MsgBox("Unexpected Error in indexing file Entity - See log", MsgBoxStyle.Critical)
                                        Return False
                                    End If
                                    indexname = dt.Rows(0).Item("IDXNAME_PARENTID").ToString
                                    idxvalue = CURRENT_PARENT_ID
                                    If LogErrorsOnly = False Then ClassLogger.Add(" - Parent-ID: " & idxvalue.ToString, False)
                                    indexierung_erfolgreich = ClassWindream.DateiIndexieren(CURRENT_FILEIN_WD, indexname, idxvalue)
                                    If indexierung_erfolgreich = False Then
                                        err = True
                                        MsgBox("Unexpected Error in indexing file Parent-ID - See log", MsgBoxStyle.Critical)
                                        Return False
                                    End If
                                End If
                            End If
                            If indexierung_erfolgreich = True Then
                                Return True
                            Else
                                MsgBox("Es gab ein Problem bei der Indexierung der Datei. Bitte prüfen sie das Log!", MsgBoxStyle.Exclamation, "Achtung:")
                                Return False
                            End If
                        End If
                    End If
                End If
            Else
                Return False
            End If



        Catch ex As Exception
            MsgBox("Unexpected error in Import_File ClassImport_windream: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function

    Public Shared Function Name_Generieren(DocTypeID As Integer)
        Try
            Dim FILE_DELIMITER, VERSION_DELIMITER, _WDOBJECTTYPE, _NewFileString As String
            Dim sql As String = "select VERSION_DELIMITER, FILE_DELIMITER FROM TBDD_MODULES where UPPER(NAME) = UPPER('Global-Indexer')"
            Dim DT1 As DataTable = ClassDatabase.Return_Datatable(sql)
            FILE_DELIMITER = DT1.Rows(0).Item("FILE_DELIMITER")
            VERSION_DELIMITER = DT1.Rows(0).Item("VERSION_DELIMITER")

            Dim err As Boolean = False
            Dim folder_Created As Boolean = False
            Dim Zielordner As String
            Dim extension As String = Path.GetExtension(CURRENT_FILENAME)
            Dim DT As DataTable = ClassDatabase.Return_Datatable("SELECT * FROM TBDD_DOKUMENTART WHERE GUID = " & DocTypeID)
            'sql_history_INSERT_INTO = "INSERT INTO TBGI_HISTORY (FILENAME_ORIGINAL,FILENAME_NEW"
            'sql_history_Index_Values = ""
            Dim AnzahlIndexe As Integer = 1
            _WDOBJECTTYPE = DT.Rows(0).Item("OBJEKTTYP")
            If folder_Created = False Then
                ' Den Zielordner erstellen
                Zielordner = DT.Rows(0).Item("ZIEL_PFAD")
                If Directory.Exists(Zielordner) = False Then
                    'Try to create the directory.
                    Directory.CreateDirectory(Zielordner)
                End If
                folder_Created = True
            End If
            '####
            ' Regulären Ausdruck zum Auslesen der Indexe definieren
            Dim preg As String = "\[%{1}[a-zA-Z0-9\!\$\&\/\(\)\=\?\,\.\-\;\:_öÖüÜäÄ\#\'\+\*\~\{\}\@\€\<\>\ ]+]{1}"
            'Namenkonvention laden
            Dim NameConv = ClassDatabase.Execute_Scalar("SELECT TOP 1 NAME_CONVENTION FROM TBPMO_WD_FORMVIEW_DOKTYPES WHERE DOCTYPE_ID = " & DocTypeID & " AND FORMVIEW_ID = " & CURRENT_FORMVIEW_ID, True)
            If IsDBNull(NameConv) Then
                ClassLogger.Add(">> Achtung: Namenskonvention is DBNull", False)
                NameConv = Path.GetFileNameWithoutExtension(CURRENT_FILENAME)
            ElseIf NameConv = String.Empty Then
                ClassLogger.Add(">> Achtung: Namenskonvention is String empty", False)
                NameConv = Path.GetFileNameWithoutExtension(CURRENT_FILENAME)
            End If
            'schonmal den gesamten Pfad laden
            Dim DATEINAME As String = Zielordner & "\" & NameConv
            If LogErrorsOnly = False Then ClassLogger.Add(">> DATEINAME: " & DATEINAME, False)

            ' 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(DATEINAME)
            '####
            ' alle Vorkommen innerhalbd er Namenkonvention durchlaufen
            For Each element As System.Text.RegularExpressions.Match In elemente
                If LogErrorsOnly = False Then ClassLogger.Add(">> element in RegeX: " & element.Value, False)
                Select Case element.Value.Substring(2, 1).ToUpper
                    'Nur automatische Indizes auswerten
                    Case "A"
                        Dim APattern = element.Value.Substring(3, element.Value.Length - 4)
                        Dim value As String

                        Select Case APattern
                            'Laufzeitvariable Record-ID
                            Case "RECORD_ID"
                                value = CURRENT_RECORD_ID
                            Case "DOKART"
                                'Laufzeitvariable Dokumentartstring
                                value = CURRENT_DOKARTSTRING
                            Case Else
                                'Ein Index der nur für die Namenkonvention herangezogen wird
                                If APattern.StartsWith("NC_") And APattern.Contains("#") Then
                                    Dim split() As String = APattern.Split("#")
                                    If split.Length = 2 Then
                                        'Die GUID des AutoIndex auslesen
                                        Dim INDEX_ID = split(1)
                                        If IsNumeric(INDEX_ID) Then
                                            Dim sql_AUTOindexresult = ClassDatabase.Execute_Scalar("SELECT SQL_RESULT FROM TBDD_INDEX_AUTOM WHERE GUID = " & INDEX_ID, True)
                                            If IsNothing(sql_AUTOindexresult) Then
                                                If LogErrorsOnly = False Then ClassLogger.Add(">> unexpected: sql_AUTOindexresult is nothing!!", False)
                                                value = ""
                                            Else
                                                If IsDBNull(sql_AUTOindexresult) Then
                                                    value = ""
                                                Else
                                                    sql_AUTOindexresult = sql_AUTOindexresult.ToString.ToUpper.Replace("@RECORD-ID", CURRENT_RECORD_ID)
                                                    Dim AUTOindexresult = ClassDatabase.Execute_Scalar(sql_AUTOindexresult, True)
                                                    If IsNothing(AUTOindexresult) Then
                                                        ClassLogger.Add(">> unexpected: AUTOindexresult is nothing!!", False)
                                                        ClassLogger.Add(">> " & sql_AUTOindexresult, False)
                                                        value = ""
                                                    Else
                                                        If IsDBNull(AUTOindexresult) Then
                                                            value = ""
                                                        Else
                                                            value = AUTOindexresult
                                                        End If
                                                    End If

                                                End If
                                            End If

                                        End If
                                    End If

                                ElseIf APattern.Contains("#") Then
                                    If LogErrorsOnly = False Then ClassLogger.Add(">> element filled with Record-Data.......: ", False)
                                    Dim split() As String = APattern.Split("#")
                                    If split.Length = 2 Then
                                        Dim CONTROL_ID = split(1)
                                        If IsNumeric(CONTROL_ID) Then
                                            Dim CONTROLVALUE = ClassControlValues.Get_Control_Value_for_ID(CONTROL_ID, CURRENT_RECORD_ID)
                                            If IsNothing(CONTROLVALUE) Then
                                                If LogErrorsOnly = False Then ClassLogger.Add(">> unexpected: CONTROLVALUE is nothing!!", False)
                                                value = ""
                                            Else
                                                If IsDBNull(CONTROLVALUE) Then
                                                    value = ""
                                                Else
                                                    value = CONTROLVALUE
                                                End If
                                            End If

                                        End If
                                    End If

                                End If
                        End Select

                        If value <> String.Empty Then
                            DATEINAME = DATEINAME.Replace(element.Value, value)
                            _NewFileString = DATEINAME
                            If LogErrorsOnly = False Then ClassLogger.Add(">> Actual NEWFILESTRING: " & _NewFileString, False)
                            ' sql_history_INSERT_INTO = sql_history_INSERT_INTO & ", INDEX" & AnzahlIndexe.ToString
                            AnzahlIndexe += 1
                            ' sql_history_Index_Values = sql_history_Index_Values & ", '" & value & "'"
                        Else
                            err = True
                        End If
                    Case "V"
                        Dim datetemp As String
                        Dim _Month As String = My.Computer.Clock.LocalTime.Month
                        If _Month.Length = 1 Then
                            _Month = "0" & _Month
                        End If
                        Dim _day As String = My.Computer.Clock.LocalTime.Day
                        If _day.Length = 1 Then
                            _day = "0" & _day
                        End If
                        Dim type = element.Value '.ToUpper.Replace("[v%", "")
                        type = type.Replace("[%v", "")
                        type = type.Replace("]", "")
                        Select Case type
                            Case "YY_MM_DD"
                                datetemp = My.Computer.Clock.LocalTime.Year.ToString.Substring(2) & "_" & _Month & "_" & _day
                            Case "YYMMDD"
                                datetemp = My.Computer.Clock.LocalTime.Year.ToString.Substring(2) & _Month & _day
                            Case "YYYY_MM_DD"
                                datetemp = My.Computer.Clock.LocalTime.Year & "_" & _Month & "_" & _day
                            Case "DD_MM_YY"
                                datetemp = _day & "_" & _Month & "_" & My.Computer.Clock.LocalTime.Year.ToString.Substring(2)
                            Case "DD_MM_YYYY"
                                datetemp = _day & "_" & _Month & "_" & My.Computer.Clock.LocalTime.Year.ToString
                            Case "DD.MM.YY"
                                datetemp = _day & "." & _Month & "." & My.Computer.Clock.LocalTime.Year.ToString.Substring(2)
                            Case "DD_MM_YYYY"
                                datetemp = _day & "_" & _Month & "_" & My.Computer.Clock.LocalTime.Year
                            Case "DD.MM.YYYY"
                                datetemp = _day & "." & _Month & "." & My.Computer.Clock.LocalTime.Year
                            Case "YYYY_MM"
                                datetemp = My.Computer.Clock.LocalTime.Year & "_" & _Month
                            Case "MM_YYYY"
                                datetemp = _Month & "_" & My.Computer.Clock.LocalTime.Year
                            Case "OFilename"
                                DATEINAME = DATEINAME.Replace(element.Value, Path.GetFileNameWithoutExtension(CURRENT_FILENAME))

                        End Select
                        If datetemp <> "" Then
                            DATEINAME = DATEINAME.Replace(element.Value, datetemp)
                        End If
                        _NewFileString = DATEINAME
                    Case Else
                        ClassLogger.Add(" - Achtung - in der Namenkonvention wurde ein Element gefunden welches nicht zugeordnet werden kann!" & vbNewLine & "Elementname: " & element.Value.ToUpper)
                        MsgBox("Achtung - in der Namenkonvention wurde ein Element gefunden welches nicht zugeordnet werden kann!" & vbNewLine & "Elementname: " & element.Value.ToUpper, MsgBoxStyle.Exclamation, "Fehler bei Name generieren:")
                End Select
            Next
            Try
                Dim version As Integer = 1
                Dim Stammname As String = DATEINAME.Replace(VERSION_DELIMITER, "")
                Dim _neuername As String = DATEINAME.Replace(VERSION_DELIMITER, "")
                'Dim MoveFilename As String = DATEINAME.Replace(element.Value, "")
                'Überprüfen ob File existiert
                If File.Exists(_neuername & extension) = False Then
                    _NewFileString = _neuername
                Else
                    Do While File.Exists(_neuername & extension)
                        version = version + 1
                        _neuername = Stammname & VERSION_DELIMITER & version
                        _NewFileString = _neuername
                    Loop
                End If
            Catch ex As Exception
                ClassLogger.Add(" - Fehler bei Versionieren der Datei - Fehler: " & vbNewLine & ex.Message)
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Umbenennnen der Datei:")
                err = True
            End Try
            CURRENT_NEWFILENAME = _NewFileString & extension
            'False oder True zurückgeben
            If err = False Then
                Return True
            Else
                MsgBox("Fehler während der Dateinamengenerierung. Bitte überprüfen Sie das Log", MsgBoxStyle.Exclamation)
                Return False
            End If

        Catch ex As Exception
            ClassLogger.Add(" - Unvorhergesehener Fehler bei Name_Generieren - Fehler: " & vbNewLine & ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Allgemeiner Fehler bei Name_Generieren:")
            Return False
        End Try

    End Function
End Class
