Imports System.IO
Imports System.Globalization
Imports System.Threading
Imports DigitalData.Modules.Windows
Imports DigitalData.Modules.License
Imports DigitalData.Modules.Base
Imports DigitalData.GUIs.Common
Imports DevExpress.LookAndFeel

Public Class frmStart
    Public LicenseManager As LicenseManagerLegacy
    Private Const WM_WINDOWPOSCHANGING As Integer = &H46

    Private IndexForm As frmIndex

    Private FileDrop As FileDrop
    Private DroppedFiles As List(Of FileDrop.DroppedFile)
    Private FormHelper As FormHelper

    'Private DroppedFiles As List(Of FileDrop.DroppedFile)

    Protected Overrides Sub WndProc(ByRef m As Message)
        ' Listen for operating system messages
        Select Case m.Msg
            Case WM_WINDOWPOSCHANGING
                Window.SnapToDesktopBorder(Me, m.LParam)
        End Select

        MyBase.WndProc(m)
    End Sub

    Public Sub New()
        Dim splash As New frmSplash()
        splash.ShowDialog()
        Thread.CurrentThread.CurrentUICulture = New CultureInfo(USER_LANGUAGE)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        FormHelper = New FormHelper(LOGCONFIG, Me)
    End Sub

#Region "=== FORM EVENTS ==="

    Private Sub frmStart_Load(sender As Object, e As EventArgs) Handles Me.Load

        Cursor = Cursors.WaitCursor
        Try
            LOGGER.Debug("frmStart_Load ...")
            Try
                IndexForm = New frmIndex()
            Catch ex As Exception
                LOGGER.Error(ex)
                LOGGER.Warn($"Error while initializing frmIndex: {ex.Message}")
            End Try

            LOGGER.Debug("Load frmIndex ready")
            FileDrop = New FileDrop(LOGCONFIG, "fileFLOW")
            LOGGER.Debug("Load FileDrop ready")
            'Lizenz abgellaufen, überprüfen ob User Admin ist
            If LICENSE_COUNT < USERCOUNT_LOGGED_IN Then
                If USER_IS_ADMIN = True Then
                    LOGGER.Info(">> User is Admin - Timer will be started")
                    If USER_LANGUAGE = "de-DE" Then
                        MsgBox("Sie haben nun 3 Minuten Zeit eine neue Lizenz zu vergeben!", MsgBoxStyle.Information)
                    Else
                        MsgBox("You now got 3 minutes to update the license!", MsgBoxStyle.Information)
                    End If

                    'Timer starten
                    If TimerClose3Minutes.Enabled = False Then
                        TimerClose3Minutes.Start()
                    End If
                End If
            End If
            If DOCTYPE_COUNT_ACTUAL > LICENSE_DOCTYPE_COUNT Then
                If USER_IS_ADMIN = True Then
                    LOGGER.Info(">> User is Admin - Timer will be started")
                    If USER_LANGUAGE = "de-DE" Then
                        MsgBox("Sie haben nun 3 Minuten Zeit eine neue Lizenz zu vergeben!", MsgBoxStyle.Information)
                    Else
                        MsgBox("You now got 3 minutes to update the license!", MsgBoxStyle.Information)
                    End If

                    'Timer starten
                    If TimerClose3Minutes.Enabled = False Then
                        TimerClose3Minutes.Start()
                    End If
                End If
            End If
            ' SetLanguage()
            If USER_IS_ADMIN = True Then
                'ToolStripSeparator1.Visible = True
                'AdministrationToolStripMenuItem.Visible = True
                buttonAdmin.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
            Else
                'ToolStripSeparator1.Visible = False
                'AdministrationToolStripMenuItem.Visible = False
                buttonAdmin.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            End If
            DATABASE_ECM.ExecuteNonQuery("DELETE FROM TBGI_FILES_USER WHERE UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')")
            LOGGER.Debug("Load almost ready, now Config ...")
            If CONFIG.Config.MyFormsDesign <> "" Then
                UserLookAndFeel.Default.SetSkinStyle(CONFIG.Config.MyFormsDesign)
            End If

            TopMost = True

        Catch ex As Exception
            MsgBox("Unexpected Error in Load-Form" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            LOGGER.Error(ex)

        End Try
        Cursor = Cursors.Default
    End Sub

    Private Sub frmStart_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        ' SetLanguage()
        If START_INCOMPLETE = True Then
            If LICENSE_COUNT = 0 And LICENSE_EXPIRED = True Then

            Else
                Me.Close()
            End If
        Else
            TimerFolderWatch.Start()
        End If
        Opacity = 0.7

        CURRENT_DT_REGEX = DATABASE_ECM.GetDatatable("SELECT * FROM TBGI_FUNCTION_REGEX")

        Start_Folderwatch()
        ClassWindowLocation.LoadFormLocationSize(Me, LoadSize:=False)
        Try
            'Me.LabelControl1.Location = New Point(13, 37)
        Catch ex As Exception
            'Me.btnChoosefiles.Location = New Point(269, 37)
        End Try
    End Sub

    Private Sub frmStart_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Try
            If START_INCOMPLETE = False Then
                Dim Sql = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_ID & " AND MODULE= 'fileFLOW'"
                DATABASE_ECM.ExecuteNonQuery(Sql)
            End If
            ClassWindowLocation.SaveFormLocationSize(Me)
        Catch ex As Exception
            MsgBox("Unexpected Error in Closing Application: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

        Try
            If Not IsNothing(IndexForm) Then
                IndexForm.DisposeViewer()
                IndexForm.Dispose()
            End If
        Catch ex As Exception
            LOGGER.Error(ex)
        End Try

        If Not IsNothing(WINDREAM) AndAlso WINDREAM.SessionLoggedin = True Then
            LOGGER.Debug("Closing frmStart - Now logging out of windream session...")
            Try
                WINDREAM.Session.Logout()
                LOGGER.Debug("windream session logged out successfully.")
            Catch ex As Exception
                LOGGER.Warn("Error while logging out windream session: " & ex.Message)
                LOGGER.Error(ex)
            End Try
        End If
    End Sub
#End Region

#Region "=== DRAG DROP ==="

    Private Sub frmMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
        DragDropForm(e)
    End Sub

    Private Sub LabelControl1_DragDrop(sender As Object, e As DragEventArgs) Handles LabelControl1.DragDrop
        DragDropForm(e)
    End Sub

    Private Sub frmMain_DragEnter(sender As Object, e As DragEventArgs) Handles Me.DragEnter
        Drag_Enter(sender, e)
    End Sub

    Private Sub LabelControl1_DragEnter(sender As Object, e As DragEventArgs) Handles LabelControl1.DragEnter
        '  PictureEdit1.Visible = True
        ' PictureEdit1.Dock = DockStyle.Fill
        Drag_Enter(sender, e)

    End Sub

    Sub DragDropForm(e As DragEventArgs)

        Dim frmCollection = Application.OpenForms
        If frmCollection.OfType(Of frmIndexFileList).Any Then
            MsgBox("Please index the active file/mail first!", MsgBoxStyle.Exclamation, "Drag 'n Drop not allowed!")
            Exit Sub
        End If
        'Erstmal alles löschen
        DATABASE_ECM.ExecuteNonQuery("DELETE FROM TBGI_FILES_USER WHERE UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')")

        ' This timer prevents the cursor from hanging because all of the remaing functions will be called in the timer thread
        DroppedFiles = FileDrop.GetFiles(e)
        If DroppedFiles.Count > 0 Then
            TimerCheckDroppedFiles.Start()
        End If
    End Sub

    Private Sub TimerCheckDroppedFiles_Tick(sender As Object, e As EventArgs) Handles TimerCheckDroppedFiles.Tick
        TimerCheckDroppedFiles.Stop()
        Check_Dropped_Files(DroppedFiles)
    End Sub

    Sub Drag_Enter(sender As Object, e As DragEventArgs)
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.All
            ' Console.WriteLine("DragEnter ...DragDrop")
        ElseIf e.Data.GetDataPresent("FileGroupDescriptor") Then
            'handle a message dragged from Outlook
            e.Effect = DragDropEffects.Copy
            ' Console.WriteLine("DragEnter ...OutlookMessage")
        ElseIf e.Data.GetDataPresent("aryFileGroupDescriptor") AndAlso (e.Data.GetDataPresent("FileContents")) Then
            e.Effect = DragDropEffects.Copy
            ' Console.WriteLine("DragEnter ...Attachment from Outlook")
        Else
            'otherwise, do not handle
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Sub Check_Dropped_Files(pDroppedFiles As List(Of FileDrop.DroppedFile))
        Try
            DATABASE_ECM.ExecuteNonQuery($"DELETE FROM TBGI_FILES_USER WHERE WORKED = 1 AND UPPER(USER@WORK) = UPPER('{Environment.UserName}')")

            For Each oDroppedFile In pDroppedFiles
                LOGGER.Info("Checking Dropped File: [{0}]", oDroppedFile.FilePath)
                Dim oDropType = oDroppedFile.DropType
                Dim oFileName = oDroppedFile.FilePath

                If ClassIndexFunctions.CheckDuplicateFiles(Me, oFileName, "Manuelle Ablage", oDropType) Then
                    FILE_HANDLER.Decide_FileHandle(oFileName, oDropType)
                End If
            Next

            Dim sql As String = $"SELECT * FROM TBGI_FILES_USER WHERE WORKED = 0 AND UPPER(USER@WORK) = UPPER('{Environment.UserName}')"
            DTACTUAL_FILES = Nothing
            DTACTUAL_FILES = DATABASE_ECM.GetDatatable(sql)
            ABORT_INDEXING = False

            Dim oOnlyFilesFromFilesystem = True
            For Each oRow As DataRow In DTACTUAL_FILES.Rows
                If oRow.Item("HANDLE_TYPE") <> "|DROPFROMFSYSTEM|" Then
                    oOnlyFilesFromFilesystem = False
                    Exit For
                End If
            Next

            If DTACTUAL_FILES.Rows.Count > 1 And oOnlyFilesFromFilesystem = False Then
                frmIndexFileList.ShowDialog()
                LOGGER.Debug("Email Indexing Dialog closed, checking for files to be indexed")

                DTACTUAL_FILES = Nothing
                DTACTUAL_FILES = DATABASE_ECM.GetDatatable(sql)
            End If

            If DTACTUAL_FILES.Rows.Count = 0 Then
                LOGGER.Debug("No files to be indexed, aborting!")

                If USER_LANGUAGE = "de-DE" Then
                    MessageBox.Show("Es wurden keine Dateien für die Indexierung ausgewählt. Der Indexierungsvorgang wird beendet.", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)
                Else
                    MessageBox.Show("You did not select any files for indexing. Indexing will be stopped.", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)
                End If
            End If

            For Each oRow As DataRow In DTACTUAL_FILES.Rows
                Dim oFileString As String = oRow.Item("FILENAME2WORK")
                Dim oFileGuid = oRow.Item("GUID")
                Dim oFileHash = oRow.ItemEx("FILE_HASH", "")
                LOGGER.Info("Processing user file {0}", oFileString)

                CURRENT_FILENAME = oFileString
                CURRENT_WORKFILE_GUID = oFileGuid
                CURRENT_WORKFILE = oFileString
                CURRENT_WORKFILE_HASH = oFileHash

                LOGGER.Info(">> CURRENT_WORKFILE: " & CURRENT_WORKFILE)
                If IO.File.Exists(CURRENT_WORKFILE) = True And DTACTUAL_FILES.Rows.Count > 0 Then
                    Open_IndexDialog()
                Else
                    LOGGER.Warn("Trying to index non-existent file [{0}]", CURRENT_WORKFILE)
                End If

                ' If multi-indexing is active, all files have been indexed by now, so we can leave the loop
                If MULTIINDEXING_ACTIVE Then
                    Exit For
                End If
            Next

            Show()
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox("Unexpected Error in Check_Dropped_Files:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)

        Finally
            ' Clear all temp files after indexing
            FILE_HANDLER.Clear_Tempfiles()
            EMAIL.Clear_TempFiles()
            FileDrop.RemoveTempDirectory()

        End Try
    End Sub

    Private Sub btnChoosefiles_Click(sender As Object, e As EventArgs)
        Try
            Dim oFileName As String
            Dim oOpenFileDialog As New OpenFileDialog With {
                .RestoreDirectory = True,
                .Multiselect = True
            }

            If oOpenFileDialog.ShowDialog() = DialogResult.OK Then
                'TODO: REMOVE
                'ClassFileDrop.FilesDropped.Clear()

                Dim oDroppedFiles As New List(Of FileDrop.DroppedFile)

                For Each oFileName In oOpenFileDialog.FileNames
                    LOGGER.Info(">> Chosen File: " & oFileName)

                    'TODO: REMOVE
                    'ClassFileDrop.FilesDropped.Add("|DROPFROMFSYSTEM|" & oFileName)

                    Dim oFile = New FileDrop.DroppedFile(oFileName) With {
                        .FileFormat = FileDrop.FileFormat.LocalFile
                    }
                    oDroppedFiles.Add(oFile)
                Next

                'TimerCheckDroppedFiles.Start()
                Check_Dropped_Files(oDroppedFiles)
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Choose Files for Indexing:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
#End Region

#Region "=== MENU ==="
    Private Sub GlobalIndexerEinstellungenToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Try
            Me.Hide()
            frmAdministration.ShowDialog()
            Me.Show()
        Catch ex As Exception
            MsgBox("Fehler in der Administration:" & vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.Critical, Text)
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub HistoryIndexierteDateienToolStripMenuItem_Click(sender As Object, e As EventArgs)
        frmHistory.ShowDialog()
    End Sub

    Private Sub InfoToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Me.TopMost = False
        frmAbout.ShowDialog()
        Me.TopMost = True
    End Sub

    Private Sub AdministrationToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Try
            Me.Hide()
            frmAdministration.ShowDialog()
            Me.Show()
        Catch ex As Exception
            MsgBox("Fehler in der Administration:" & vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.Critical, Text)
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub GrundeinstellungenToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Me.TopMost = False
        frmConfig_Basic.ShowDialog()
        'Wurde die Sprache in der Konfiguration geändert
        If LANGUAGE_CHANGED = True Then
            Try
                If USER_LANGUAGE = "de-DE" Then
                    MsgBox("Zur letzendlichen Neukonfiguration der Sprache ist ein Neustart notwendig!", MsgBoxStyle.Information, Text)
                Else
                    MsgBox("For the final changing of language, a restart is required!", MsgBoxStyle.Information, Text)
                End If
                Application.Restart()
            Catch ex As Exception
                LOGGER.Error(ex)
                MsgBox("Please restart the application manually.", MsgBoxStyle.Information, Text)
            End Try
        Else
            Start_Folderwatch()
            Me.TopMost = True
        End If
    End Sub
#End Region

#Region "=== FOLDERWATCH ==="
    Sub Start_Folderwatch()
        If CURRENT_FOLDERWATCH = String.Empty Then
            FW_started = False
        End If

        If CURRENT_SCAN_FOLDERWATCH = String.Empty Then
            CONFIG.Config.FolderWatchScanStarted = False
            CONFIG.Save()
        End If

        If CURRENT_FOLDERWATCH <> "" Or CURRENT_SCAN_FOLDERWATCH <> "" Then
            If FWFunction_STARTED = True Then
                labelFolderwatch.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
            Else
                labelFolderwatch.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
            End If

            Try
                If CONFIG.Config.FolderWatchScanStarted = True Then
                    LOGGER.Info(">> FWSCAN started - Checking file:" & CURRENT_SCAN_FOLDERWATCH)
                    Dim fileEntries As String() = Directory.GetFiles(CURRENT_SCAN_FOLDERWATCH)
                    ' Process the list of files found in the directory.
                    Dim oFileName As String
                    For Each oFileName In fileEntries
                        LOGGER.Info(">> Scanfolder after startup: Checking file:" & oFileName)
                        For Each row As DataRow In DTEXCLUDE_FILES.Rows
                            Dim content As String = row.Item(0).ToString.ToLower
                            If oFileName.ToLower.Contains(content) Then
                                Exit Sub
                            End If
                        Next
                        Dim oHandleType As String
                        If oFileName.ToLower.EndsWith(".msg") Then
                            oHandleType = "|FW_OUTLOOK_MESSAGE|"
                        Else
                            oHandleType = "|FW_SIMPLEINDEXER|"
                        End If
                        'Die Datei übergeben
                        LOGGER.Info(">> Adding file from Scanfolder after startup:" & oFileName)

                        If ClassIndexFunctions.CheckDuplicateFiles(Me, oFileName, "FolderWatch/Scan") Then
                            FILE_HANDLER.Decide_FileHandle(oFileName, oHandleType)
                        End If
                    Next oFileName

                Else
                    LOGGER.Info(">> FWSCAN not started")
                End If
            Catch ex As Exception
                LOGGER.Info(">> Error while starting folderwatch scan: " & ex.Message)
                LOGGER.Error(ex)
            End Try

            Try
                If FW_started = True Then
                    LOGGER.Info(">> FW_started started - Checking file:" & CURRENT_FOLDERWATCH)
                    Dim fileEntries As String() = Directory.GetFiles(CURRENT_FOLDERWATCH)
                    ' Process the list of files found in the directory.
                    Dim oFileName As String
                    For Each oFileName In fileEntries
                        LOGGER.Info(">> Folderwach after startup: Checking file:" & oFileName)
                        For Each row As DataRow In DTEXCLUDE_FILES.Rows
                            Dim content As String = row.Item(0).ToString.ToLower
                            If oFileName.ToLower.Contains(content) Then
                                Exit Sub
                            End If
                        Next
                        Dim handleType As String
                        If oFileName.ToLower.EndsWith(".msg") Then
                            handleType = "|FW_OUTLOOK_MESSAGE|"
                        Else
                            handleType = "|FW_SIMPLEINDEXER|"
                        End If
                        'Die Datei übergeben
                        LOGGER.Info(">> Adding file from Folderwatch after startup:" & oFileName)

                        If ClassIndexFunctions.CheckDuplicateFiles(Me, oFileName, "FolderWatch/Scan") Then
                            FILE_HANDLER.Decide_FileHandle(oFileName, handleType)
                        End If
                    Next oFileName
                Else
                    LOGGER.Info(">> FW_started not started")
                End If
            Catch ex As Exception
                LOGGER.Info(">> Error while starting folderwatch: " & ex.Message)
                LOGGER.Error(ex)
            End Try

            If TimerFolderWatch.Enabled = False Then
                TimerFolderWatch.Start()
            End If
        End If

    End Sub

    Private Sub TimerFolderWatch_Tick(sender As Object, e As EventArgs) Handles TimerFolderWatch.Tick
        If DATABASE_ECM.DBInitialized = False Then
            TimerFolderWatch.Enabled = False

            Dim title = "Critical Error"
            Dim message = $"Database could not be reached. File Flow will NOT work without a database!{vbCrLf}{vbCrLf}Please check your connection.{vbCrLf}The Application will exit now."

            If USER_LANGUAGE = "de-DE" Then
                title = "Kritischer Fehler"
                message = $"Die Datenbank konnte nicht erreicht werden. File Flow funktioniert NICHT ohne Datenbankverbindung{vbCrLf}{vbCrLf}Bitte überprüfen Sie Ihre Netzwerkverbindung oder benachrichtigen Sie Ihren Administrator.{vbCrLf}Die Anwendung wird nun geschlossen."
            End If

            Dim result = MsgBox(message, MsgBoxStyle.Critical, title)

            If result = MsgBoxResult.Ok Then
                Application.ExitThread()
            End If
        Else
            Try
                ' JenneJ, 11.02.2019:
                ' Keine Folderwatch Dateien verarbeiten, wenn gerade Indexiert wird, 
                ' dadurch würden die Globalen Variablen überschrieben
                ' und in Folge die falschen Dateien Indexiert!
                If INDEXING_ACTIVE Or MULTIINDEXING_ACTIVE Then
                    Exit Sub
                End If

                If FW_started = True Or CONFIG.Config.FolderWatchScanStarted = True Then
                    'Prüfen ob alle Files abgearbeitet wurden
                    Dim oSql = $"SELECT * FROM TBGI_FILES_USER WHERE WORKED = 0 AND HANDLE_TYPE like '%|FW%' AND USER@WORK = '{Environment.UserName}'"
                    DTACTUAL_FILES = DATABASE_ECM.GetDatatable(oSql)

                    If DTACTUAL_FILES.Rows.Count > 0 Then
                        ABORT_INDEXING = False
                        Me.TimerFolderWatch.Stop()
                        If LOGCONFIG.Debug Then
                            Clipboard.Clear()
                            Clipboard.SetText(oSql, TextDataFormat.Text)

                            'MsgBox("DEBUG - Check TBGI_FILES_USER if necessary. Command copied to Clipboard")
                        End If

                        For Each oRow As DataRow In DTACTUAL_FILES.Rows
                            Dim FILEGUID = oRow.Item("GUID")
                            If ABORT_INDEXING = True Then
                                Exit For
                            End If
                            Dim FileForWork As String = oRow.Item("FILENAME2WORK")
                            LOGGER.Info(">> In Timer Folderwatch - File: " & FileForWork)
                            Dim fileInUse As Boolean = FILE_HANDLER.IsFileInUse(FileForWork)
                            Dim fileexists As Boolean = System.IO.File.Exists(FileForWork)
                            If fileInUse = False Then
                                If fileexists = True Then
                                    CURRENT_FILENAME = FileForWork
                                    CURRENT_WORKFILE = FileForWork
                                    CURRENT_WORKFILE_GUID = oRow.Item("GUID")
                                    CURRENT_WORKFILE_HASH = oRow.Item("FILE_HASH")

                                    Open_IndexDialog()
                                Else
                                    LOGGER.Info($">> File [{FileForWork}] not existing - row from TBGI_FILES_USER will be deleted!")
                                    Dim del = String.Format("DELETE FROM TBGI_FILES_USER WHERE GUID = {0}", FILEGUID)
                                    DATABASE_ECM.ExecuteNonQuery(del)
                                End If
                            Else
                                LOGGER.Info(">> file '" & FileForWork & "' could not be opened exclusively - fileInUse!")
                            End If

                        Next
                        Me.TimerFolderWatch.Start()
                    End If
                    labelFolderwatch.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
                Else
                    labelFolderwatch.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
                End If
            Catch ex As Exception
                If ex.Message.Contains("Sammlung wurde geändert") Or ex.Message.Contains("Enumeration") Then

                Else
                    MsgBox("Error in Work FolderWatch-File:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                End If

            End Try
        End If
    End Sub
#End Region

    Sub Open_IndexDialog()
        Try
            Hide()
            IndexForm.ShowDialog()
        Catch ex As Exception
            LOGGER.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        Finally
            Show()
        End Try
    End Sub



    Private Sub TimerClose3Minutes_Tick(sender As Object, e As EventArgs) Handles TimerClose3Minutes.Tick
        If LICENSE_EXPIRED = True Or LICENSE_COUNT < USERCOUNT_LOGGED_IN Then
            If USER_LANGUAGE = "de-DE" Then
                MsgBox("File Flow wird nun geschlossen, weil keine neue Lizenzdaten eingegeben wurden!", MsgBoxStyle.Information)
            Else
                MsgBox("File Flow will now be closed, cause no new license was updated!", MsgBoxStyle.Information)
            End If

            Me.Close()
        Else
            TimerClose3Minutes.Stop()
        End If
    End Sub



    Private Sub frmStart_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
        If e.KeyCode = Keys.F12 Then
            If START_INCOMPLETE Then
                frmLicense.ShowDialog()
            End If
        End If
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles buttonAdmin.ItemClick
        Try
            Me.Hide()
            frmAdministration.ShowDialog()
            Me.Show()
        Catch ex As Exception
            MsgBox("Fehler in der Administration:" & vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.Critical, Text)
            LOGGER.Error(ex)
        End Try
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        Me.TopMost = False
        frmConfig_Basic.ShowDialog()
        'Wurde die Sprache in der Konfiguration geändert
        If LANGUAGE_CHANGED = True Then
            Try
                If USER_LANGUAGE = "de-DE" Then
                    MsgBox("Zur letzendlichen Neukonfiguration der Sprache ist ein Neustart notwendig!", MsgBoxStyle.Information, Text)
                Else
                    MsgBox("For the final changing of language, a restart is required!", MsgBoxStyle.Information, Text)
                End If
                Application.Restart()
            Catch ex As Exception
                LOGGER.Error(ex)
                MsgBox("Please restart the application manually.", MsgBoxStyle.Information, Text)
            End Try
        Else
            Start_Folderwatch()
            Me.TopMost = True
        End If
    End Sub

    Private Sub BarButtonItem3_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        frmHistory.ShowDialog()
    End Sub

    Private Sub BarButtonItem4_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem4.ItemClick
        Me.TopMost = False
        frmAbout.ShowDialog()
        Me.TopMost = True
    End Sub

    Private Sub LabelControl1_Click(sender As Object, e As EventArgs) Handles LabelControl1.Click
        Try
            Dim oFileName As String
            Dim oOpenFileDialog As New OpenFileDialog With {
                .RestoreDirectory = True,
                .Multiselect = True
            }

            If oOpenFileDialog.ShowDialog() = DialogResult.OK Then
                'TODO: REMOVE
                'ClassFileDrop.FilesDropped.Clear()

                Dim oDroppedFiles As New List(Of FileDrop.DroppedFile)

                For Each oFileName In oOpenFileDialog.FileNames
                    LOGGER.Info(">> Chosen File: " & oFileName)

                    'TODO: REMOVE
                    'ClassFileDrop.FilesDropped.Add("|DROPFROMFSYSTEM|" & oFileName)

                    Dim oFile = New FileDrop.DroppedFile(oFileName) With {
                        .FileFormat = FileDrop.FileFormat.LocalFile
                    }
                    oDroppedFiles.Add(oFile)
                Next

                'TimerCheckDroppedFiles.Start()
                Check_Dropped_Files(oDroppedFiles)
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Choose Files for Indexing:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub LabelControl1_DragLeave(sender As Object, e As EventArgs) Handles LabelControl1.DragLeave
        'PictureEdit1.Visible = False
    End Sub

    Private Sub frmStart_GiveFeedback(sender As Object, e As GiveFeedbackEventArgs) Handles Me.GiveFeedback

    End Sub
End Class