Imports System.IO
Imports Independentsoft
Imports System.Threading


Public Class ClassFolderWatcher
    Public Shared FolderWatcher_SCAN As FileSystemWatcher
    Public Shared NEW_FILES As Boolean = True
    Public Shared Function Restart_FolderWatchSCAN()

        Try
            If FolderWatcher_SCAN.EnableRaisingEvents = True Then
                'Gestartet also Stoppen
                FolderWatcher_SCAN.EnableRaisingEvents = False
                FWSCAN_started = False
                'FolderWatch neu instanzieren
                FolderWatcher_SCAN = New System.IO.FileSystemWatcher(CURRENT_SCAN_FOLDERWATCH, "*.*")
                LOGGER.Warn("FolderWatchScan neu instanziert")
                FolderWatcher_SCAN.IncludeSubdirectories = CURRENT_SCAN_FOLDERWATCH_SD
                FolderWatcher_SCAN.EnableRaisingEvents = True
                AddHandler FolderWatcher_SCAN.Created, AddressOf OnCreated
                FWSCAN_started = True
                SaveMySettingsValue("FWSCAN_started", "True", "ConfigMain")

            End If
        Catch ex As Exception
            MsgBox("Error in Restart_FolderWatchSCAN:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Function
    Public Shared Function StartStop_FolderWatchSCAN()
        Try
            If CURRENT_SCAN_FOLDERWATCH = "" Then
                MsgBox("Bitte definieren Sie einen Überwachungsordner für Scan-Eingänge:", MsgBoxStyle.Exclamation)
                Return False
            End If
            If FolderWatcher_SCAN Is Nothing Then
                FolderWatcher_SCAN = New System.IO.FileSystemWatcher(CURRENT_SCAN_FOLDERWATCH, "*.*")
                LOGGER.Info("FolderWatch Scan Gestartet")
                FolderWatcher_SCAN.IncludeSubdirectories = CURRENT_SCAN_FOLDERWATCH_SD
                FolderWatcher_SCAN.EnableRaisingEvents = True
                AddHandler FolderWatcher_SCAN.Created, AddressOf OnCreated
                FWSCAN_started = True
                SaveMySettingsValue("FWSCAN_started", "True", "ConfigMain")
                Return 1
            End If
            If FolderWatcher_SCAN.EnableRaisingEvents = False Then
                ' Dim watcher As New FileSystemWatcher()
                ' watcher.Path = CURRENT_FOLDERWATCH
                FolderWatcher_SCAN = New System.IO.FileSystemWatcher(CURRENT_SCAN_FOLDERWATCH, "*.*")
                LOGGER.Info("FolderWatch Scan Gestartet")
                FolderWatcher_SCAN.IncludeSubdirectories = CURRENT_SCAN_FOLDERWATCH_SD
                FolderWatcher_SCAN.EnableRaisingEvents = True
                AddHandler FolderWatcher_SCAN.Created, AddressOf OnCreated
                FWSCAN_started = True
                SaveMySettingsValue("FWSCAN_started", "True", "ConfigMain")
                Return 1
            Else
                'Gestartet also Stoppen
                FolderWatcher_SCAN.EnableRaisingEvents = False
                FWSCAN_started = False
                LOGGER.Info("FolderWatch Scan gestoppt")
                SaveMySettingsValue("FWSCAN_started", "False", "ConfigMain")
                Return 0
            End If

        Catch ex As Exception
            MsgBox("Error in StartStop_FolderWatchSCAN:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return 99
        End Try
    End Function
    Private Shared Sub OnCreated(source As Object, e As FileSystemEventArgs)
        Try
            For Each row As DataRow In DTEXCLUDE_FILES.Rows
                Dim content As String = row.Item(0).ToString.ToLower
                If e.FullPath.ToLower.Contains(content) Then
                    Exit Sub
                End If
            Next

            Dim handleType As String
            If e.FullPath.EndsWith(".msg") Then
                handleType = "SCAN_OUTLOOK_MESSAGE"
            Else
                handleType = "SCAN"
            End If
            'Die Datei übergeben
            LOGGER.Debug("OnCreated-File:" & e.FullPath)
            If FileExistsinDropTable(CURRENT_FILENAME) = False Then
                Insert_USER_File(e.FullPath, handleType)
            Else
                Console.WriteLine("File existiert bereits")
            End If
            ClassHelper.Create_USER_FILE_TABLE()
            NEW_FILES = True
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in folder_watch_Created")
        End Try

    End Sub

    Public Shared Function FileExistsinDropTable(Filename As String)
        Dim check As String
        Try
            check = "SELECT COUNT(*) FROM TBPMO_FILES_USER WHERE UPPER(FILENAME2WORK) = UPPER('" & Filename & "') AND WORKED = 0"
            Dim result = MYDB_ECM.GetScalarValue(check)
            Return result
        Catch ex As Exception
            MsgBox("Error in FileExistsinDropTable - Error-Message:" & vbNewLine & ex.Message & vbNewLine & "SQL-Command:" & vbNewLine & check, MsgBoxStyle.Critical)
            Return Nothing
        End Try

    End Function
    Public Shared Function Insert_USER_File(filename As String, handleType As String)
        Try
            Dim filename_only As String = Path.GetFileName(filename)
            Dim ins As String = String.Format("INSERT INTO TBPMO_FILES_USER (FILENAME2WORK, USER_WORK,HANDLE_TYPE,FILENAME_ONLY) VALUES ('{0}','{1}','{2}','{3}')", filename, USER_USERNAME, handleType, filename_only)
            Return MYDB_ECM.ExecuteNonQuery(ins)
        Catch ex As Exception
            MsgBox("Unexpected Error in Insert Scan-File: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Public Shared Function DELETE_SCAN_File(filename As String)
        Try
            Dim filename_only As String = Path.GetFileName(filename)
            Dim del As String = String.Format("DELETE FROM TBPMO_FILES_USER WHERE UPPER(FILENAME2WORK) = UPPER('{0}')", filename)
            Return MYDB_ECM.ExecuteNonQuery(del)
        Catch ex As Exception
            MsgBox("Unexpected Error in DELETE_SCAN_File: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Public Shared Function DELETE_SCAN_File_User()
        Try
            Dim del As String = String.Format("DELETE FROM TBPMO_FILES_USER WHERE UPPER(USER_WORK) = UPPER('{0}') AND HANDLE_TYPE = 'SCAN'", USER_USERNAME)
            Return MYDB_ECM.ExecuteNonQuery(del)
        Catch ex As Exception
            MsgBox("Unexpected Error in DELETE_SCAN_File_User: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function

    Public Shared Function Check_Scan_Files()
        Try
            Dim sql As String = String.Format("select * from TBPMO_FILES_USER where HANDLE_TYPE = 'SCAN' and WORKED = 0 AND UPPER(USER_WORK) = '{0}'", USER_USERNAME)
            Dim DT As DataTable = MYDB_ECM.GetDatatable(sql)
            For Each row As DataRow In DT.Rows
                If System.IO.File.Exists(row.Item("FILENAME2WORK")) = False Then
                    DELETE_SCAN_File(row.Item("FILENAME2WORK"))
                End If
            Next
            CURRENT_SCAN_TABLE = MYDB_ECM.GetDatatable(sql)
        Catch ex As Exception
            MsgBox("Unexpected Error in DELETE_SCAN_File_User: " & ex.Message, MsgBoxStyle.Critical)
            Return Nothing
        End Try
    End Function
End Class
