Option Explicit On

Imports System.IO
Imports System.Runtime.InteropServices
Imports DevExpress.XtraSplashScreen
Imports DigitalData.GUIs.ClipboardWatcher
Imports DigitalData.GUIs.ZooFlow.ClassConstants
Imports DigitalData.GUIs.ZooFlow.ClipboardWatcher
Imports DigitalData.Modules
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Language.Utils
Imports DigitalData.Modules.Messaging
Imports DigitalData.Modules.Windows

Public Class frmFlowForm


    ' Constants
    Private Const OPACITY_INITIAL = 0
    Private Const OPACITY_HIDDEN = 0.65
    Private Const OPACITY_SHOWN = 0.85

    Private DTIDB_SEARCHES As DataTable

    ' Common Helpers Classes
    Private Init As ClassInit
    Private FileClass As Filesystem.File

    ' Globix Helper Classes
    Private FileDrop As ClassFileDrop
    Private FileHandle As ClassFilehandle
    Private FolderWatch As ClassFolderwatcher

    ' ClipboardWatcher Helper Classes
    Private ClassWindow As Window
    Private ProfileFilter As ProfileFilter
    Private ProfileLoader As ClassProfileLoader
    Private Animator As New Animator() With {
        .PopupColor = Color.FromArgb(255, 214, 49),
        .PopupOpacity = 0.8,
        .PopupSize = New Size(100, 30)
    }

    ' Runtime Flags
    Private ApplicationLoading As Boolean = True
    Private IDBSearchActive As Boolean = False

    ' Runtime Variables
    Private ESCHitCount As Integer = 0
    Private IndexForm As frmGlobix_Index
    Private AdminForm As frmAdmin_Start


    ' Events
    Public Event ClipboardChanged As EventHandler(Of IDataObject)
    Private WithEvents HotkeyClass As Hotkey
    Private WithEvents Watcher As Watcher = Watcher.Singleton

    Public Sub New()
        MyBase.New(My.LogConfig)

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' === Hide form initially ===
        Opacity = OPACITY_INITIAL
    End Sub

    Private Sub frmFlowForm_Load(sender As Object, e As EventArgs) Handles Me.Load
        ' === Show Splash Screen ===
        SplashScreenManager.ShowForm(Me, GetType(frmSplash), False, False)

        ' === Initialization ===
        Init = New ClassInit(My.LogConfig, Me)
        AddHandler Init.Completed, AddressOf Init_Completed
        Init.InitializeApplication()

        ' Register Form as Sidebar
        My.Application.Sidebar = New Sidebar(Handle)
        My.Application.Sidebar.RegisterSidebar(My.UIConfig.SidebarScreen)
    End Sub

    Private Sub Init_Completed(sender As Object, e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        ' === Initialization Complete ===
        ApplicationLoading = False
        SplashScreenManager.CloseForm(False)

        ' === Setup Timers ===
        AddHandler TimerRefreshData.Tick, AddressOf TimerRefreshData_Tick
        TimerRefreshData.Enabled = True

        ' === Register As Event Listener ===
        EventBus.Instance.Register(Me)

        ' === Set Form Properties ===
        TopMost = True
        AllowDrop = True
        ShowInTaskbar = False
        Opacity = OPACITY_SHOWN
        Location = My.UIConfig.FlowForm.Location

        ' === Setup Event Handlers ===
        AddHandler KeyDown, AddressOf frmFlowForm_KeyDown
        AddHandler KeyUp, AddressOf frmFlowForm_KeyDown

        AddHandler Watcher.ClipboardChanged, AddressOf Watcher_ClipboardChanged

        Dim oSQL = My.Queries.Common.FNIDB_GET_SEARCH_PROFILES(My.Application.User.UserId, My.Application.User.Language)
        Dim oDatatable As DataTable = My.Database.GetDatatableIDB(oSQL)
        PictureBoxSearch1.Visible = False
        If Not IsNothing(oDatatable) OrElse oDatatable.Rows.Count > 0 Then
            IDBSearchActive = True
            DTIDB_SEARCHES = oDatatable
            PictureBoxSearch1.Visible = True
        End If

        If My.Application.ModulesActive.Contains(MODULE_CLIPBOARDWATCHER) Then
            Try
                ClassWindow = New Window(My.LogConfig)
                HotkeyClass = New Hotkey(Me)

                'Add Toggle Hotkey
                HotkeyClass.AddHotKey(Keys.T, Hotkey.ModfierKey.MOD_CONTROL, HOTKEY_TOGGLE_WATCHER)

                ' Add Trigger Hotkey

                'TODO: Configure Hotkey
                Dim oSearchKey As String = "D"
                Dim oFunctionKey As String = "CTRL"

                Dim oConverter As New KeysConverter
                Dim oObject As Object = oConverter.ConvertFromString(oSearchKey)
                Dim oKeyCode As Keys = oObject

                Select Case oFunctionKey
                    Case "CTRL"
                        HotkeyClass.AddHotKey(oKeyCode, Hotkey.ModfierKey.MOD_CONTROL, HOTKEY_TRIGGER_WATCHER)
                    Case "SHIFT"
                        HotkeyClass.AddHotKey(oKeyCode, Hotkey.ModfierKey.MOD_SHIFT, HOTKEY_TRIGGER_WATCHER)
                    Case "ALT"
                        HotkeyClass.AddHotKey(oKeyCode, Hotkey.ModfierKey.MOD_ALT, HOTKEY_TRIGGER_WATCHER)
                    Case "WIN"
                        HotkeyClass.AddHotKey(oKeyCode, Hotkey.ModfierKey.MOD_WIN, HOTKEY_TRIGGER_WATCHER)
                End Select

                AddHandler HotkeyClass.HotKeyPressed, AddressOf HotkeyClass_HotKeyPressed

                ProfileLoader = New ClassProfileLoader(My.LogConfig, My.Database)
                ProfileLoader.LoadProfiles()
            Catch ex As Exception
                ShowErrorMessage(ex)
            End Try
        Else
            My.Application.ClipboardWatcher.MonitoringActive = False
            Logger.Info("Clipboard Watcher Module is not active. Hotkey Monitoring will be disabled!")
        End If

        If My.Application.ModulesActive.Contains(MODULE_GLOBAL_INDEXER) Then
            FileDrop = New ClassFileDrop(My.LogConfig)
            FileHandle = New ClassFilehandle(My.LogConfig)
            FolderWatch = New ClassFolderwatcher(My.LogConfig)

            Dim oFileExclusions As New ClassExclusions()
            If oFileExclusions.Load(My.Application.Globix.PATH_FileExclusions) = False Then
                If My.Application.User.Language = "de-DE" Then
                    MsgBox("Die Ausschlusskriterien für Dateien in Folderwatch konnten nicht angelegt werden!", MsgBoxStyle.Information)
                Else
                    MsgBox("File-Exclusions in Folderwatch could not be created!", MsgBoxStyle.Information)
                End If

            End If

            Init_Folderwatch()
            Start_Folderwatch()
            GlobixToolStripMenuItem.Visible = True

        End If

        oSQL = "SELECT * FROM TBIDB_ATTRIBUTE"
        My.Tables.DTIDB_ATTRIBUTE = My.Database.GetDatatable("TBIDB_ATTRIBUTE", "SELECT * FROM TBIDB_ATTRIBUTE", EDMI.API.Constants.DatabaseType.IDB)

        Me.Cursor = Cursors.Default
    End Sub

    Public Sub Init_Folderwatch()
        Try
            Dim oSql As String = "SELECT FOLDER_PATH FROM TBGI_FOLDERWATCH_USER WHERE FOLDER_TYPE = 'DEFAULT' AND USER_ID = " & My.Application.User.UserId
            Dim oDT = My.Database.GetDatatable("TBGI_FOLDERWATCH_USER", oSql, EDMI.API.Constants.DatabaseType.ECM, $"FOLDER_TYPE = 'DEFAULT' AND USER_ID = {My.Application.User.UserId}")

            If oDT.Rows.Count = 0 Then
                'Throw New ApplicationException("No Default Path configured for User!")
                Logger.Warn("No Default Path configured for User. Skipping.")
                Exit Sub
            End If

            Dim oFolderWatchPath = oDT.Rows.Item(0).Item("FOLDER_PATH")
            oFolderWatchPath = NotNull(oFolderWatchPath, String.Empty).ToString

            If oFolderWatchPath = String.Empty Then
                Logger.Info("Init_Folderwatch: folderwatchPath is empty")
                My.Application.Globix.Folderwatchstarted = False
                My.UIConfig.Globix.FolderWatchStarted = False
                My.UIConfigManager.Save()

            End If

            If Not IO.Directory.Exists(oFolderWatchPath) Then
                Logger.Info("Init_Folderwatch: folderwatchPath does not exists or is invalid path")
                My.Application.Globix.Folderwatchstarted = False
                My.UIConfig.Globix.FolderWatchStarted = False
                My.UIConfigManager.Save()

            End If

            My.Application.Globix.CurrentFolderWatchPath = oFolderWatchPath
            My.Application.Globix.Folderwatchstarted = True
            'FWFunction_STARTED = True
            FolderWatch.StartStop_FolderWatch()
        Catch ex As Exception
            ShowErrorMessage(ex)
        End Try

        Try
            Dim oSql As String = "SELECT FOLDER_PATH FROM TBGI_FOLDERWATCH_USER WHERE FOLDER_TYPE = 'SCAN' AND USER_ID = " & My.Application.User.UserId
            Dim oFolderwatchScanPath = My.Database.GetScalarValueECM(oSql)

            oFolderwatchScanPath = IIf(IsDBNull(oFolderwatchScanPath), "", oFolderwatchScanPath)

            If oFolderwatchScanPath = String.Empty Then
                Logger.Info("Init_Folderwatch: folderwatchScanPath is empty")
                My.UIConfig.Globix.FolderWatchStarted = False
                My.UIConfigManager.Save()
                Exit Sub
            End If

            If Not IO.Directory.Exists(oFolderwatchScanPath) Then
                Logger.Info("Init_Folderwatch: folderwatchScanPath does not exists or is invalid path")
                My.UIConfig.Globix.FolderWatchStarted = False
                My.UIConfigManager.Save()
                Exit Sub
            End If

            My.Application.Globix.CURRENT_SCAN_FOLDERWATCH = oFolderwatchScanPath


            'FWFunction_STARTED = True
            FolderWatch.StartStop_FolderWatchSCAN()
        Catch ex As Exception
            ShowErrorMessage(ex)
        End Try

    End Sub

    Private Sub TimerRefreshData_Tick(sender As Object, e As EventArgs)
        'TODO: Refresh Data
    End Sub

    Private Sub frmFlowForm_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
        If e.KeyCode = Keys.Escape Then
            If ESCHitCount > 0 Then
                ExitZooflow()
            Else
                ESCHitCount += 1
            End If
        ElseIf e.KeyCode = Keys.D AndAlso (e.Control) Then
            If My.Application.ModulesActive.Contains(ClassConstants.MODULE_ZOOFLOW) Then
                MsgBox("Search")
            End If
        End If
    End Sub

    Sub ExitZooflow()
        Dim oResult As DialogResult = MessageBox.Show("Are you sure you want to close ZooFlow?", "Exit Zooflow", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If oResult = DialogResult.Yes Then
            Close()
        Else
            ESCHitCount = 0
        End If
    End Sub

    Public Sub OnEvent(Params As Object)
        Logger.Debug("OnEvent called!")
    End Sub
    Private Sub PictureBox1_Click(sender As Object, e As EventArgs)
        frmSearchNeu.Show()

        'Open_FlowSearch()
    End Sub
    Sub Open_FlowSearch()
        Cursor = Cursors.WaitCursor
        If TheFormIsAlreadyLoaded("frmFlowSearch") Then
            Cursor = Cursors.Default
            Exit Sub
        End If
        Dim oSQLFlowSearch As String = ""
        For Each oRow As DataRow In My.Tables.DTIDB_COMMON_SQL.Rows
            If oRow.Item("TITLE") = SQLCMD_FLOW_SEARCH_LOWER_LIMIT Then
                oSQLFlowSearch = oRow.Item("SQL_COMMAND")

            End If
        Next
        If oSQLFlowSearch <> String.Empty Then
            oSQLFlowSearch = oSQLFlowSearch.Replace("@USER_ID", My.Application.User.UserId)
            oSQLFlowSearch = oSQLFlowSearch.Replace("@LANGUAGE_ID", My.Application.User.LanguageId)
            oSQLFlowSearch = oSQLFlowSearch.Replace("@LANGUAGE", My.Application.User.Language)
            Dim oForm As New frmFlowSearch(oSQLFlowSearch)
            oForm.Show()
            oForm.BringToFront()
        End If

        Cursor = Cursors.Default
    End Sub

    Private Sub PictureBoxSearch1_Click(sender As Object, e As EventArgs) Handles PictureBoxSearch1.Click
        Open_FlowSearch()
    End Sub

    Private Sub ZooFlowBeendenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ZooFlowBeendenToolStripMenuItem.Click
        ExitZooflow()
    End Sub

    Private Sub VerwaltungToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VerwaltungToolStripMenuItem.Click
        Me.Cursor = Cursors.WaitCursor
        AdminForm = New frmAdmin_Start()

        frmAdmin_Start.Show()
        If TimerCheckActiveForms.Enabled = False Then
            TimerCheckActiveForms.Enabled = True
        End If

        Me.Cursor = Cursors.Default
    End Sub

    Private Sub frmFlowForm_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
        PictureBoxDragDrop.Image = My.Resources._1_LOGO_ZOO_FLOW_DROP3

        e.Effect = DragDropEffects.Copy
        Drag_Enter(sender, e)
    End Sub

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

    Private Sub frmFlowForm_DragLeave(sender As Object, e As EventArgs) Handles Me.DragLeave
        PictureBoxDragDrop.Image = My.Resources._1_LOGO_ZOO_FLOW1
    End Sub

    Private Sub PictureBoxAbo_MouseEnter(sender As Object, e As EventArgs) Handles PictureBoxAbo.MouseEnter
        PictureBoxAbo.Image = My.Resources._2_ZOO_FLOW_Abo_MouseOver
    End Sub

    Private Sub PictureBoxAbo_MouseLeave(sender As Object, e As EventArgs) Handles PictureBoxAbo.MouseLeave
        PictureBoxAbo.Image = My.Resources._2_ZOO_FLOW_Abo
    End Sub

    Private Sub PictureBoxAbo_Click(sender As Object, e As EventArgs) Handles PictureBoxAbo.Click
        Cursor = Cursors.WaitCursor
        If TheFormIsAlreadyLoaded("frmPreSearch") Then
            Cursor = Cursors.Default
            Exit Sub
        End If
        Dim oForm2 As New frmSearchPredefined()
        oForm2.Show()
        Cursor = Cursors.Default
    End Sub
    Private Function TheFormIsAlreadyLoaded(ByVal pFormName As String) As Boolean

        TheFormIsAlreadyLoaded = False

        For Each frm As Form In Application.OpenForms
            If frm.Name.Equals(pFormName) Then
                TheFormIsAlreadyLoaded = True
                Exit Function
            End If
        Next

    End Function
    Private Function FormLoaded_Visible() As Boolean
        For Each frm As Form In Application.OpenForms
            If frm.Name.Equals("frmSearchStart") Or frm.Name.Equals("frmGlobix_Index") Or frm.Name.Equals("frmAdmin_Start") Then
                Return False
            End If
        Next

        'TimerCheckActiveForms.Enabled = False
        Return True
    End Function

    Private Sub DatenbankverbindungToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DatenbankverbindungToolStripMenuItem.Click
        frmConfigDatabase.ShowDialog()
    End Sub



    'Private Sub TimerCheckActiveForms_Tick(sender As Object, e As EventArgs) Handles TimerCheckActiveForms.Tick
    '    Visible = FormLoaded_Visible()
    '    If Visible = False Then Exit Sub
    'End Sub

    Private Sub NotifyIcon_DoubleClick(sender As Object, e As EventArgs) Handles NotifyIcon.DoubleClick
        If Visible = False Then
            Visible = True
        Else
            Visible = False
            'TimerCheckActiveForms.Enabled = False
        End If
    End Sub

    Private Sub PictureBox1_DragEnter(sender As Object, e As DragEventArgs) Handles PictureBoxDragDrop.DragEnter
        Drag_Enter(sender, e)
    End Sub

    Sub Drag_Enter(sender As Object, e As DragEventArgs)
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.All

        ElseIf e.Data.GetDataPresent("FileGroupDescriptor") Then 'handle a message dragged from Outlook
            e.Effect = DragDropEffects.Copy

        ElseIf e.Data.GetDataPresent("aryFileGroupDescriptor") AndAlso (e.Data.GetDataPresent("FileContents")) Then
            e.Effect = DragDropEffects.Copy

        Else
            'otherwise, do not handle
            e.Effect = DragDropEffects.None

        End If
    End Sub
    Sub DragDropForm(e As DragEventArgs)
        If Not My.Application.ModulesActive.Contains(ClassConstants.MODULE_GLOBAL_INDEXER) Then
            Exit Sub
        End If
        If TheFormIsAlreadyLoaded("frmIndexFileList") Then
            Cursor = Cursors.Default
            MsgBox("Please index the active file first!", MsgBoxStyle.Exclamation, "Drag 'n Drop not allowed!")
            Exit Sub
        End If

        'Erstmal alles löschen
        My.Database.ExecuteNonQueryECM("DELETE FROM TBGI_FILES_USER WHERE UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')")

        If FileDrop.Drop_File(e) = True Then
            TimerCheckDroppedFiles.Start()
            Me.Cursor = Cursors.WaitCursor
        End If
    End Sub

    Private Sub PictureBox1_DragDrop(sender As Object, e As DragEventArgs) Handles PictureBoxDragDrop.DragDrop
        DragDropForm(e)
    End Sub

    Private Async Sub TimerCheckDroppedFiles_Tick(sender As Object, e As EventArgs) Handles TimerCheckDroppedFiles.Tick
        If Not My.Application.ModulesActive.Contains(ClassConstants.MODULE_GLOBAL_INDEXER) Then
            Exit Sub
        End If

        TimerCheckDroppedFiles.Stop()
        Await Globix_Check_Dropped_Files()
        Me.Cursor = Cursors.Default
    End Sub
    Private Async Function Globix_Check_Dropped_Files() As Threading.Tasks.Task
        Try
            Await My.Database.ExecuteNonQueryECMAsync($"DELETE FROM TBGI_FILES_USER WHERE WORKED = 1 AND UPPER(USER@WORK) = UPPER('{Environment.UserName}')")
            Dim i As Integer

            For Each pFile As String In FileDrop.files_dropped
                If Not pFile Is Nothing Then
                    Logger.Info(" Check Drop-File: " & pFile.ToString)
                    Dim handleType As String = pFile.Substring(0, pFile.LastIndexOf("|") + 1)
                    Dim filename As String = pFile.Substring(pFile.LastIndexOf("|") + 1)
                    If FileHandle.CheckDuplicateFiles(filename, "Manuelle Ablage") Then
                        FileHandle.Decide_FileHandle(filename, handleType)
                        i += 1
                    End If
                End If
            Next

            Dim sql As String = "SELECT * FROM TBGI_FILES_USER WHERE WORKED = 0 AND UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')"
            My.Application.Globix.DTACTUAL_FILES = Nothing
            My.Application.Globix.DTACTUAL_FILES = Await My.Database.GetDatatableECMAsync(sql)
            My.Application.Globix.ABORT_INDEXING = False

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

            If My.Application.Globix.DTACTUAL_FILES.Rows.Count > 1 And oOnlyFilesFromFilesystem = False Then
                frmGlobix_IndexFileList.ShowDialog()
                My.Application.Globix.DTACTUAL_FILES = Nothing
                My.Application.Globix.DTACTUAL_FILES = My.Database.GetDatatableECM(sql)
            End If

            For Each oRow As DataRow In My.Application.Globix.DTACTUAL_FILES.Rows
                Dim oFilePath As String = oRow.Item("FILENAME2WORK").ToString
                Dim oFileId As Integer = oRow.Item("GUID")

                My.Application.Globix.CurrentWorkfile = New Globix.Models.WorkFile With {
                    .Id = oFileId,
                    .FilePath = oFilePath
                }

                Logger.Info(" CURRENT_WORKFILE: {0}", My.Application.Globix.CurrentWorkfile)
                If IO.File.Exists(My.Application.Globix.CurrentWorkfile.FilePath) = True And My.Application.Globix.DTACTUAL_FILES.Rows.Count > 0 Then
                    Globix_Open_IndexDialog()
                    PictureBoxDragDrop.Image = My.Resources._1_LOGO_ZOO_FLOW1
                End If
            Next
            Show()
        Catch ex As Exception
            ShowErrorMessage(ex)
            Show()
        End Try

    End Function
    Sub Globix_Open_IndexDialog()
        Try
            IndexForm = New frmGlobix_Index(My.LogConfig)
            NotifyIconReset()
            AddHandler IndexForm.FormClosed, AddressOf GlobixClosed
            IndexForm.Show()
            Cursor = Cursors.Default

            'If TimerCheckActiveForms.Enabled = False Then
            '    TimerCheckActiveForms.Enabled = True
            'End If
        Catch ex As Exception
            ShowErrorMessage(ex)
        End Try
    End Sub
    Sub NotifyIconReset()
        NI_TYPE = "INFO"
        NI_MESSAGE = String.Empty
    End Sub
    Sub GlobixClosed()
        Try
            If NI_MESSAGE = String.Empty Then
                Exit Sub
            End If

            Dim oNIType = 1
            Select Case NI_TYPE
                Case "INFO"
                    oNIType = 1
                Case "ERROR"
                    oNIType = 3
            End Select
            NotifyIcon.ShowBalloonTip(30000, NI_TITLE, NI_MESSAGE, oNIType)
        Catch ex As Exception
            ShowErrorMessage(ex)
        End Try
    End Sub
    Sub Start_Folderwatch()
        If My.Application.Globix.CurrentFolderWatchPath = String.Empty Then
            My.Application.Globix.Folderwatchstarted = False
        End If

        If My.Application.Globix.CURRENT_SCAN_FOLDERWATCH = String.Empty Then
            My.UIConfigManager.Config.Globix.FolderWatchScanStarted = False
            My.UIConfigManager.Save()
        End If

        If My.Application.Globix.CurrentFolderWatchPath <> "" Or My.Application.Globix.CURRENT_SCAN_FOLDERWATCH <> "" Then
            Try
                If My.UIConfigManager.Config.Globix.FolderWatchScanStarted = True Then
                    Logger.Info("FWSCAN started - Checking file:" & My.Application.Globix.CURRENT_SCAN_FOLDERWATCH)
                    Dim fileEntries As String() = Directory.GetFiles(My.Application.Globix.CURRENT_SCAN_FOLDERWATCH)
                    ' Process the list of files found in the directory.
                    Dim fileName As String
                    For Each fileName In fileEntries
                        Logger.Info("Scanfolder after startup: Checking file:" & fileName)
                        For Each row As DataRow In My.Application.Globix.DTEXCLUDE_FILES.Rows
                            Dim content As String = row.Item(0).ToString.ToLower
                            If fileName.ToLower.Contains(content) Then
                                Exit Sub
                            End If
                        Next
                        Dim handleType As String
                        If fileName.ToLower.EndsWith(".msg") Then
                            handleType = "|FW_OUTLOOK_MESSAGE|"
                        Else
                            handleType = "|FW_SIMPLEINDEXER|"
                        End If
                        'Die Datei übergeben
                        Logger.Info(" Adding file from Scanfolder after startup:" & fileName)
                        If FileHandle.CheckDuplicateFiles(fileName, "FolderWatch/Scan") Then
                            FileHandle.Decide_FileHandle(fileName, handleType)
                        Else
                            Logger.Info("Scanfolder Startup: File already exists:" & fileName)
                        End If
                    Next fileName

                Else
                    Logger.Info("FWSCAN not started")
                End If
            Catch ex As Exception
                ShowErrorMessage(ex)
            End Try

            Try
                If My.Application.Globix.Folderwatchstarted = True Then
                    Logger.Info("Folderwatchstarted - Checking file:" & My.Application.Globix.CurrentFolderWatchPath)
                    Dim fileEntries As String() = Directory.GetFiles(My.Application.Globix.CurrentFolderWatchPath)
                    ' Process the list of files found in the directory.
                    Dim fileName As String
                    For Each fileName In fileEntries
                        Logger.Info("Folderwach after startup: Checking file:" & fileName)
                        For Each row As DataRow In My.Application.Globix.DTEXCLUDE_FILES.Rows
                            Dim content As String = row.Item(0).ToString.ToLower
                            If fileName.ToLower.Contains(content) Then
                                Exit Sub
                            End If
                        Next
                        Dim handleType As String
                        If fileName.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:" & fileName)
                        If FileHandle.CheckDuplicateFiles(fileName, "FolderWatch/Scan") Then
                            FileHandle.Decide_FileHandle(fileName, handleType)
                        Else
                            Logger.Info("Folderwatch Startup: File already exists:" & fileName)
                        End If
                    Next fileName

                Else
                    Logger.Info("Folderwatch not started")
                End If
            Catch ex As Exception
                ShowErrorMessage(ex)
            End Try

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

    End Sub



    Private Sub frmFlowForm_ResizeEnd(sender As Object, e As EventArgs) Handles Me.ResizeEnd
        My.UIConfig.FlowForm.Location = Location
        My.UIConfigManager.Save()
    End Sub

    Private Sub TimerFolderwatch_Tick_1(sender As Object, e As EventArgs) Handles TimerFolderwatch.Tick

        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 My.Application.Globix.INDEXING_ACTIVE Or My.Application.Globix.MULTIINDEXING_ACTIVE Then
                Exit Sub
            End If

            If My.Application.Globix.Folderwatchstarted = True Or My.UIConfig.Globix.FolderWatchScanStarted = True Then
                'Prüfen ob alle Files abgearbeitet wurden
                Dim sql = "SELECT * FROM TBGI_FILES_USER WHERE WORKED = 0 AND HANDLE_TYPE like '%|FW%' AND UPPER(USER@WORK) = UPPER('" & Environment.UserName & "')"
                My.Application.Globix.DTACTUAL_FILES = My.Database.GetDatatableECM(sql)

                If My.Application.Globix.DTACTUAL_FILES.Rows.Count > 0 Then
                    My.Application.Globix.ABORT_INDEXING = False
                    ' Dim fil As String
                    Me.TimerFolderwatch.Stop()
                    For Each row As DataRow In My.Application.Globix.DTACTUAL_FILES.Rows
                        Dim FILEGUID = row.Item("GUID")
                        If My.Application.Globix.ABORT_INDEXING = True Then
                            Exit For
                        End If
                        Dim FileForWork As String = row.Item(1).ToString
                        Logger.Info(" In Timer Folderwatch - File: " & FileForWork)
                        Dim fileInUse As Boolean = FileHandle.IsFileInUse(FileForWork)
                        Dim fileexists As Boolean = System.IO.File.Exists(FileForWork)
                        If fileInUse = False Then
                            If fileexists = True Then
                                My.Application.Globix.CurrentWorkfile = New Globix.Models.WorkFile With {
                                    .Id = DirectCast(row.Item("GUID"), Integer),
                                    .FilePath = FileForWork
                                }

                                Globix_Open_IndexDialog()
                            Else
                                Logger.Info(" File not existing - Row will be deleted!")
                                Dim oDel = String.Format("DELETE FROM TBGI_FILES_USER WHERE GUID = {0}", FILEGUID)
                                My.Database.ExecuteNonQueryECM(oDel)
                            End If
                        Else
                            Logger.Info(" file '" & row.Item(1).ToString & "' could not be opened exclusively - fileInUse!")
                        End If

                    Next
                    Me.TimerFolderwatch.Start()
                End If
                'tslblFW.Visible = True
            Else
                'tslblFW.Visible = False
            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 Sub

    Private Sub TsiGlobixConfig_Click(sender As Object, e As EventArgs) Handles TsiGlobixConfig.Click
        frmGlobixBasicConfig.ShowDialog()
    End Sub

    Private Sub Watcher_ClipboardChanged(sender As Object, e As IDataObject)
        Dim ClipboardContents As String = Clipboard.GetText().Trim()
        Dim oState = My.Application.ClipboardWatcher

        oState.CurrentClipboardContents = ClipboardContents

        ' TODO: These messages are so fucking annoying

        'If oState.MonitoringActive = False Then
        '    Dim oMessage As String = "Clipboard Watcher is not active!"
        '    Logger.Info(oMessage)
        '    MsgBox(oMessage, MsgBoxStyle.Critical, Text)

        '    Exit Sub
        'End If

        'If oState.UserProfiles Is Nothing Then
        '    Dim oMessage As String = "User Profiles are empty!"
        '    Logger.Info(oMessage)
        '    MsgBox(oMessage, MsgBoxStyle.Critical, Text)

        '    Exit Sub
        'End If

        'If oState.ProfileProcesses Is Nothing OrElse oState.ProfileProcesses.Rows.Count = 0 Then
        '    Dim oMessage As String = "Profile Processes are empty!"
        '    Logger.Info(oMessage)
        '    MsgBox(oMessage, MsgBoxStyle.Critical, Text)

        '    Exit Sub
        'End If

        'If oState.ProfileWindows Is Nothing OrElse oState.ProfileWindows.Rows.Count = 0 Then
        '    Dim oMessage As String = "Profile Processes are empty!"
        '    Logger.Info(oMessage)
        '    MsgBox(oMessage, MsgBoxStyle.Critical, Text)

        '    Exit Sub
        'End If

        'If oState.ProfileProcesses Is Nothing OrElse oState.ProfileProcesses.Rows.Count = 0 Then
        '    Dim oMessage As String = "Profile Processes are empty!"
        '    Logger.Info(oMessage)
        '    MsgBox(oMessage, MsgBoxStyle.Critical, Text)

        '    Exit Sub
        'End If

        Dim oWindowInfo = ClassWindow.GetWindowInfo()

        Try
            ' Tree View zurücksetzen
            oState.MatchTreeView.Nodes.Clear()

            ProfileFilter = New ProfileFilter(My.LogConfig,
                oState.UserProfiles, oState.ProfileProcesses, oState.ProfileWindows, oState.ProfileControls, oState.MatchTreeView)
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox("Fehler beim Laden der Profile. Möglicherweise liegt ein Konfigurationsfehler vor. Fehlermeldung: " & ex.Message, MsgBoxStyle.Critical, Text)
        End Try

        Try
            Dim oProfiles = ProfileFilter.Profiles
            Dim oEnvironment = ClassEnvironment.GetEnvironment()

            ' Filter by Clipboard Contents
            oProfiles = ProfileFilter.FilterProfilesByClipboardRegex(oProfiles, ClipboardContents)
            oProfiles = ProfileFilter.LogRemainingProfiles(oProfiles, "FilterProfilesByClipboardRegex")

            ' Filter by Process Name
            oProfiles = ProfileFilter.FilterProfilesByProcess(oProfiles, oWindowInfo.ProcessName)
            oProfiles = ProfileFilter.LogRemainingProfiles(oProfiles, "FilterProfilesByProcess")

            ' Filter by Window Title
            oProfiles = ProfileFilter.FilterWindowsByWindowTitleRegex(oProfiles, oWindowInfo.WindowTitle)
            oProfiles = ProfileFilter.LogRemainingProfiles(oProfiles, "FilterWindowsByWindowTitleRegex")

            ' Filter by Focused Control
            oProfiles = ProfileFilter.FilterProfilesByFocusedControl(oProfiles, ClipboardContents, Handle)
            oProfiles = ProfileFilter.LogRemainingProfiles(oProfiles, "FilterProfilesByFocusedControl")
            oState.CurrentMatchingProfiles = oProfiles.ToList()

            ' Filter by Search Results
            oProfiles = ProfileFilter.FilterProfilesBySearchResults(oProfiles, oEnvironment.Database, oEnvironment.User, ClipboardContents)
            oProfiles = ProfileFilter.LogRemainingProfiles(oProfiles, "FilterProfilesBySearchResults")

            ' Clean up Profiles
            oProfiles = ProfileFilter.ClearNotMatchedProfiles(oProfiles)
            oProfiles = ProfileFilter.ClearDuplicateProfiles(oProfiles)
            oProfiles = ProfileFilter.LogRemainingProfiles(oProfiles, "CleanUp")

            oState.CurrentProfilesWithResults = oProfiles.ToList()
        Catch ex As Exception
            Logger.Error(ex)
            MsgBox("Fehler beim Auswerten der Profile. Mehr Informationen im Log.", MsgBoxStyle.Critical, Text)
        End Try
    End Sub

    Private Sub HotkeyClass_HotKeyPressed(HotKeyID As String)
        Dim oState = My.Application.ClipboardWatcher

        Select Case HotKeyID
            Case HOTKEY_TRIGGER_WATCHER
                Animator.Highlight(Cursor.Position)

                If oState.CurrentClipboardContents = String.Empty Then
                    Logger.Info("Current Clipboard Contents is empty. Exiting.")
                    Exit Sub
                End If

                If oState.MonitoringActive = False Then
                    Logger.Info("Monitoring is inactive. Exiting.")
                    Exit Sub
                End If

                If oState.UserProfiles.Rows.Count = 0 Then
                    NotifyIcon.ShowBalloonTip(NOTIFICATION_DELAY, "ClipboardWatcher", "Es wurden keine Profile für Sie gefunden.", ToolTipIcon.Warning)

                ElseIf oState.CurrentMatchingProfiles.Count = 0 Then
                    NotifyIcon.ShowBalloonTip(NOTIFICATION_DELAY, "ClipboardWatcher", "Es wurden keine passenden Profile gefunden.", ToolTipIcon.Warning)

                ElseIf oState.CurrentProfilesWithResults.Count = 0 Then
                    NotifyIcon.ShowBalloonTip(NOTIFICATION_DELAY, "ClipboardWatcher", "Es wurden weder Dokumente noch Daten gefunden!", ToolTipIcon.Warning)

                Else
                    Dim oProfiles = oState.CurrentProfilesWithResults
                    Dim oEnvironment = My.Application.GetEnvironment()
                    Dim oParams As New DigitalData.Modules.ZooFlow.ClipboardWatcherParams With {
                        .ClipboardContents = oState.CurrentClipboardContents,
                        .MatchingProfiles = oProfiles,
                        .MatchTreeView = oState.MatchTreeView,
                        .OperationModeOverride = Modules.ZooFlow.Constants.OperationMode.ZooFlow
                    }

                    Dim oForm As New frmMatch(My.LogConfig, oEnvironment, oParams)
                    oForm.Show()

                End If

            Case HOTKEY_TOGGLE_WATCHER
                If oState.MonitoringActive = True Then
                    NotifyIcon.ShowBalloonTip(NOTIFICATION_DELAY, "ClipboardWatcher", "Clipboard-Watcher wurde deaktiviert!", ToolTipIcon.Info)

                Else
                    NotifyIcon.ShowBalloonTip(NOTIFICATION_DELAY, "ClipboardWatcher", "Clipboard-Watcher wurde aktiviert!", ToolTipIcon.Info)

                End If

                oState.MonitoringActive = Not oState.MonitoringActive

        End Select
    End Sub

    Private Sub PictureBoxPM1_Click(sender As Object, e As EventArgs) Handles PictureBoxPM1.Click
        ToastNotificationsManager1.ShowNotification(ToastNotificationsManager1.Notifications(1))
    End Sub

    Private Sub TestToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles TestToolStripMenuItem.Click
        frmtest.Show()

    End Sub

    Private Sub SucheTestToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SucheTestToolStripMenuItem.Click
        frmSearchNeu.Show()
    End Sub

    Private Sub BasisKonfigurationToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BasisKonfigurationToolStripMenuItem.Click
        frmConfigBasic.ShowDialog()
    End Sub
End Class

