Imports System.IO

Public Class frmWD_EntityImport
    Private LOCAL_IMPORTFILE As String
    Private LOCAL_NEWFILESTRING As String
    Private LOCAL_TARGET_PATH As String
    Private LOCAL_COUNTFILES As Integer
    Private Sub frmWD_EntityImport_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        My.Settings.Save()
    End Sub

    Private Sub frmWD_EntityImport_Load(sender As Object, e As EventArgs) Handles Me.Load
        Me.txtEntityString.Text = CURRENT_ENTITYSTRING
        If ClassWindream.Init = True Then
            ObjektTypenEintragen()
        End If

      


    End Sub
    Private Sub ObjektTypenEintragen()
        Try
            Dim oDokumentTyp As WINDREAMLib.WMObject
            ' Combobox leeren
            Me.cmbObjekttyp.Items.Clear()
            ' alle Objekttypen durchlaufen
            For Each oDokumentTyp In ClassWindream.GetObjecttypesAsObjects
                ' und in die Combobox eintragen
                Me.cmbObjekttyp.Items.Add(oDokumentTyp.aName)
            Next
        Catch ex As Exception
            MsgBox("Fehlernachricht:" & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Fehler beim Eintragen der Objekttypen")
        End Try

    End Sub
    Private Sub btnopenfolder_Click(sender As Object, e As EventArgs) Handles btnopenfolder.Click
        Dim fbdia As New FolderBrowserDialog
        If fbdia.ShowDialog() = DialogResult.OK Then
            txtpath.Text = fbdia.SelectedPath
        End If
    End Sub

    Private Sub btnpathWD_Click(sender As Object, e As EventArgs) Handles btnpathWD.Click
        Dim fbdia As New FolderBrowserDialog
        If fbdia.ShowDialog() = DialogResult.OK Then
            txtwindreamPath.Text = fbdia.SelectedPath
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnrunImport.Click
        If txtpath.Text <> "" And txtwindreamPath.Text <> "" Then
            LOCAL_COUNTFILES = 0
            Dim searchoption As New System.IO.SearchOption
            ListBox2.Items.Clear()
            If rbsubdirectoriesFiles.Checked Or rbSubdirectoriesFolders.Checked Then
                searchoption = IO.SearchOption.AllDirectories
            Else
                searchoption = IO.SearchOption.TopDirectoryOnly
            End If
            Dim filesarray = GetFiles(Me.txtpath.Text, Me.txtFilter.Text, txtFilter_exclude.Text, searchoption)
            For Each f As String In filesarray
                Work_File(f)
            Next
            MsgBox("Insgesamt wurden " & LOCAL_COUNTFILES.ToString & " Dateien nach windream importiert!", MsgBoxStyle.Information)
        End If
      
    End Sub
    Private Sub chkImportoptionenBackup_CheckedChanged(sender As Object, e As EventArgs) Handles chkImportoptionenBackup.CheckedChanged
        If chkImportoptionenBackup.Checked Then
            Me.txtBackupordner.Enabled = True
            Me.btnBackupordner.Enabled = True
        Else
            Me.txtBackupordner.Enabled = False
            Me.btnBackupordner.Enabled = False
        End If
    End Sub
    Public Shared Function GetFiles(path As String, searchPattern As String, excludePattern As String, searchOption As SearchOption) As String()
        Dim searchPatterns As String() = searchPattern.Split("|"c)
        Dim allFiles As New List(Of String)()
        For Each sp As String In searchPatterns
            allFiles.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption))
        Next
        'allFiles.Sort()
        Dim filesToExclude As New List(Of String)()
        searchPatterns = excludePattern.Split("|"c)
        For Each sp As String In searchPatterns
            filesToExclude.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption))
        Next

        Dim wantedFiles = allFiles.Except(filesToExclude)

        Return wantedFiles.ToArray()
    End Function
    Sub Work_File(Filepath As String)
        LOCAL_IMPORTFILE = Filepath
        Dim filestring As String

        If rbSubdirectoriesFolders.Checked = False Then
            filestring = Path.GetFileName(Filepath)
        Else
            filestring = Filepath.Replace(Me.txtpath.Text, "")
        End If
        If rbsubdirectoriesFiles.Checked Then
            filestring = Path.GetFileName(Filepath)
        End If
        Dim target As String = txtwindreamPath.Text & "\" & filestring

        Dim version As Integer = 2
        Dim Dateiname As String = Path.GetFileNameWithoutExtension(target)
        Dim extension As String = Path.GetExtension(target)

        Dim folder_Base As String = Path.GetDirectoryName(target)
        If rbSubdirectoriesFolders.Checked Then
            If Not IO.Directory.Exists(folder_Base) Then
                ' Nein! Jetzt erstellen...
                Try
                    IO.Directory.CreateDirectory(folder_Base)
                    ' Ordner wurde korrekt erstellt!
                Catch ex As Exception
                    ' Ordner wurde nich erstellt
                End Try
            End If
        End If
        Dim Stammname As String = folder_Base & "\" & Dateiname
        Dim _neuername As String = folder_Base & "\" & Dateiname
        LOCAL_TARGET_PATH = folder_Base
        'Dim MoveFilename As String = DATEINAME.Replace(element.Value, "")
        'Überprüfen ob File existiert

        Do While File.Exists(_neuername & extension)
            _neuername = Stammname & "~" & version
            LOCAL_NEWFILESTRING = _neuername
            version = version + 1
        Loop
        LOCAL_NEWFILESTRING = _neuername & extension
        WINDREAM_IMPORT()
        LOCAL_COUNTFILES += 1
    End Sub
    Private Function WINDREAM_IMPORT()
        Try
            ClassWindream._WDObjekttyp = Me.cmbObjekttyp.Text
            Dim streamresult = ClassWindream.Stream_File(LOCAL_IMPORTFILE, LOCAL_TARGET_PATH)
            'Dim type = streamresult.GetType
            If streamresult = True Then
                Dim indexierung_erfolgreich As Boolean = False

                'den Entity-Key auslesen
                Dim sql As String = "Select Top 1 * from TBPMO_WD_OBJECTTYPE where Upper(object_type) = Upper('" & ClassWindream._WDObjekttyp & "')"
                Dim dt As DataTable = 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
                                    MsgBox("Error in indexing file Entity - See log", MsgBoxStyle.Critical)
                                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
                                    MsgBox("Error in indexing file Parent-ID - See log", MsgBoxStyle.Critical)
                                End If
                            End If
                        End If
                If indexierung_erfolgreich = True Then
                    Dim error_Occured = False
                    If chkImportoptionenBackup.Checked And txtBackupordner.Text <> String.Empty Then
                        error_Occured = Create_Copy()
                    End If
                    'Die Originaldatei löschen
                    If error_Occured = False Then
                        File.Delete(LOCAL_IMPORTFILE)
                    End If

                Else
                    MsgBox("Es gab ein Problem bei der Indexierung der Datei. Bitte prüfen sie das Log!", MsgBoxStyle.Exclamation, "Achtung:")
                End If
            Else
                MsgBox("Unexpected Error in Stream2windream. Please check logfile!", MsgBoxStyle.Exclamation)
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Windream-Import:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Function
    Private Function Create_Copy()
        Try
            Dim filestring As String
            If rbSubdirectoriesFolders.Checked = False Then
                filestring = Path.GetFileName(LOCAL_IMPORTFILE)
            Else
                filestring = LOCAL_IMPORTFILE.Replace(Me.txtpath.Text, "")
            End If
            If rbsubdirectoriesFiles.Checked Then
                filestring = Path.GetFileName(LOCAL_IMPORTFILE)
            End If
            Dim target As String = txtBackupordner.Text & "\" & filestring

            Dim version As Integer = 2
            Dim Dateiname As String = Path.GetFileNameWithoutExtension(target)
            Dim extension As String = Path.GetExtension(target)

            Dim folder_Base As String = Path.GetDirectoryName(target)

            If Not IO.Directory.Exists(folder_Base) Then
                ' Nein! Jetzt erstellen...
                Try
                    IO.Directory.CreateDirectory(folder_Base)
                    ' Ordner wurde korrekt erstellt!
                Catch ex As Exception
                    ' Ordner wurde nich erstellt
                End Try
            End If

            Dim Stammname As String = folder_Base & "\" & Dateiname
            Dim _neuername As String = folder_Base & "\" & Dateiname
            LOCAL_TARGET_PATH = folder_Base
            'Dim MoveFilename As String = DATEINAME.Replace(element.Value, "")
            'Überprüfen ob File existiert
            Dim COPY_STRING As String
            Do While File.Exists(_neuername & extension)
                _neuername = Stammname & "~" & version
                COPY_STRING = _neuername
                version = version + 1
            Loop
            COPY_STRING = _neuername & extension
            File.Copy(LOCAL_IMPORTFILE, COPY_STRING)
            Return False
        Catch ex As Exception
            MsgBox("Unexpected Error in Create-Copy:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return True
        End Try
      

    End Function
    Private Sub cmbObjekttyp_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbObjekttyp.SelectedIndexChanged
        If cmbObjekttyp.SelectedIndex <> -1 Then
            Load_Indices(cmbObjekttyp.Text)
        End If
    End Sub
    Sub Load_Indices(Objecttype As String)

        'den Entity-Key auslesen
        Dim Sql = "Select Top 1 * from TBPMO_WD_OBJECTTYPE where Upper(object_type) = Upper('" & Objecttype & "')"
        Dim DT As DataTable = ClassDatabase.Return_Datatable(Sql)
        Dim count As Integer = 0
        If Not DT Is Nothing Then
            If DT.Rows.Count = 1 Then
                ListView1.Items.Clear()
                ListView1.Items.Add(DT.Rows(0).Item("IDXNAME_ENTITYID").ToString)
                ListView1.Items(count).SubItems.Add(CURRENT_FORM_ID)
                ListView1.Items.Add(DT.Rows(0).Item("IDXNAME_PARENTID").ToString)
                ListView1.Items(count + 1).SubItems.Add(CURRENT_PARENT_ID)
            End If
        End If
    End Sub

    Private Sub frmWD_EntityImport_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If My.Settings.WD_ENTITYIMP_OBJECTTYPE <> String.Empty Then
            Load_Indices(My.Settings.WD_ENTITYIMP_OBJECTTYPE)
        End If
        If My.Settings.WD_ENTITYIMP_SAFETYPATH <> String.Empty Then
            Me.chkImportoptionenBackup.Checked = True
        End If
    End Sub
End Class