Imports System.IO
Imports DigitalData.Modules.Logging

Public Class ClassFolderwatcher
    Inherits Base.BaseClass

    Public Shared FWFolderWatcher As FileSystemWatcher
    Public Shared FWScan As FileSystemWatcher

    Private ReadOnly FileHandle As ClassFilehandle

    Public Sub New(pLogConfig As LogConfig)
        MyBase.New(pLogConfig)
        FileHandle = New ClassFilehandle(pLogConfig)
    End Sub

    Public Function Restart_FolderWatch() As Boolean
        Try
            If FWFolderWatcher.EnableRaisingEvents = True Then
                'Gestartet also Stoppen
                FWFolderWatcher.EnableRaisingEvents = False
                My.Application.Globix.Folderwatchstarted = False

                FWFolderWatcher = StartFolderwatcherForPath(My.Application.Globix.CurrentFolderWatchPath)
                My.Application.Globix.Folderwatchstarted = True
                My.UIConfig.Globix.FolderWatchStarted = True
                My.UIConfigManager.Save()
            End If
            Return True
        Catch ex As Exception
            Logger.Info($"Error in Restart_FolderWatch: {ex.Message}")
            Logger.Error(ex.Message)
            Return False
        End Try
    End Function
    Public Sub Restart_FolderWatchSCAN()
        Try
            If FWScan.EnableRaisingEvents = True Then
                'Gestartet also Stoppen
                FWScan.EnableRaisingEvents = False

                'FolderWatch neu instanzieren
                FWScan = StartFolderwatcherForPath(My.Application.Globix.CURRENT_SCAN_FOLDERWATCH)

                My.UIConfig.Globix.FolderWatchScanStarted = True
                My.UIConfigManager.Save()
            End If
        Catch ex As Exception
            Logger.Info($"Error in Restart_FolderWatchSCAN: {ex.Message}")
            Logger.Error(ex.Message)
        End Try
    End Sub
    Public Sub StartStop_FolderWatch()
        Try
            If FWFolderWatcher Is Nothing OrElse FWFolderWatcher.EnableRaisingEvents = False Then
                ' Folderwatch neu instanzieren
                FWFolderWatcher = StartFolderwatcherForPath(My.Application.Globix.CurrentFolderWatchPath)
                My.Application.Globix.Folderwatchstarted = True
                My.UIConfig.Globix.FolderWatchStarted = True
                My.UIConfigManager.Save()

            End If

            If FWFolderWatcher.EnableRaisingEvents = True Then
                'Gestartet also Stoppen
                FWFolderWatcher.EnableRaisingEvents = False
                My.Application.Globix.Folderwatchstarted = False
                Logger.Info(" >> FolderWatch gestoppt")
                My.UIConfig.Globix.FolderWatchStarted = False
                My.UIConfigManager.Save()
            End If
        Catch ex As Exception
            Logger.Error(ex.Message)
            MsgBox("Error in StartStop_FolderWatch:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Public Function StartStop_FolderWatchSCAN() As Integer
        Try
            If My.Application.Globix.CURRENT_SCAN_FOLDERWATCH = "" Then
                If FWFolderWatcher.EnableRaisingEvents = True Then
                    Stop_FWSCAN()
                    Return 0
                Else
                    If My.Application.User.Language = "de-DE" Then
                        MsgBox("Bitte definieren Sie einen Überwachungsordner für Scan-Eingänge:", MsgBoxStyle.Exclamation)
                    Else
                        MsgBox("Please define a watchfolder for Scanning:", MsgBoxStyle.Exclamation)
                    End If

                    Return False
                End If
            End If
            If FWScan Is Nothing Then
                FWScan = New FileSystemWatcher(My.Application.Globix.CURRENT_SCAN_FOLDERWATCH, "*.*")
                Logger.Info(" >> FolderWatch Scan Gestartet")
                FWScan.IncludeSubdirectories = False
                FWScan.EnableRaisingEvents = True
                AddHandler FWScan.Created, AddressOf OnCreated
                My.UIConfig.Globix.FolderWatchScanStarted = True
                My.UIConfigManager.Save()
                Return 1
            End If
            If FWScan.EnableRaisingEvents = False Then
                ' Dim watcher As New FileSystemWatcher()
                ' watcher.Path = CURRENT_FOLDERWATCH
                FWScan = New System.IO.FileSystemWatcher(My.Application.Globix.CURRENT_SCAN_FOLDERWATCH, "*.*")
                Logger.Info(" >> FolderWatch Scan Gestartet")
                FWScan.IncludeSubdirectories = False
                FWScan.EnableRaisingEvents = True
                AddHandler FWScan.Created, AddressOf OnCreated
                My.UIConfig.Globix.FolderWatchScanStarted = True
                My.UIConfigManager.Save()
                Return 1
            Else
                'Gestartet also Stoppen
                FWScan.EnableRaisingEvents = False
                Logger.Info(" >> FolderWatch Scan gestoppt")
                'SaveConfigValue("FWSCAN_started", "False")
                My.UIConfig.Globix.FolderWatchScanStarted = False
                My.UIConfigManager.Save()
                Return 0
            End If

        Catch ex As Exception
            Logger.Error(ex.Message)
            MsgBox("Error in StartStop_FolderWatchSCAN:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return 99
        End Try
    End Function
    Public Function Stop_FWSCAN()
        If FWFolderWatcher.EnableRaisingEvents = True Then
            'Gestartet also Stoppen
            FWFolderWatcher.EnableRaisingEvents = False
            My.Application.Globix.Folderwatchstarted = False
            Logger.Info(" >> FolderWatch gestoppt")
            'SaveConfigValue("my.Application.Globix.Folderwatchstarted", "False")
            My.UIConfig.Globix.FolderWatchStarted = True
            My.UIConfigManager.Save()
            Return True
        Else
            Return False
        End If
    End Function

    Private Function StartFolderwatcherForPath(pPath As String) As FileSystemWatcher
        Dim oWatcher = New FileSystemWatcher(pPath, "*.*") With {
            .IncludeSubdirectories = False,
            .EnableRaisingEvents = True
        }
        AddHandler oWatcher.Created, AddressOf OnCreated
        Logger.Debug("Folder Watcher started for Path [{0}]", pPath)

        My.UIConfig.Globix.FolderWatchScanStarted = True
        My.UIConfigManager.Save()

        Return oWatcher
    End Function

    Private Sub OnCreated(source As Object, e As FileSystemEventArgs)
        Try
            If Not IsNothing(My.Application.Globix.DTEXCLUDE_FILES) Then
                For Each row As DataRow In My.Application.Globix.DTEXCLUDE_FILES.Rows
                    Dim content As String = row.Item(0).ToString.ToLower
                    If e.FullPath.ToLower.Contains(content) Then
                        Exit Sub
                    End If
                Next
            End If


            Dim handleType As String
            If e.FullPath.ToLower.EndsWith(".msg") Then
                handleType = "|FW_OUTLOOK_MESSAGE|"
            Else
                handleType = "|FW_SIMPLEINDEXER|"
            End If
            'Die Datei übergeben
            Logger.Info(">> OnCreated-File:" & e.FullPath)

            If FileHandle.CheckDuplicateFiles(e.FullPath, "FolderWatch/Scan") Then
                FileHandle.Decide_FileHandle(e.FullPath, handleType)
            Else
                Logger.Info(">> Folderwatcher: File already exists:" & e.FullPath)
            End If

        Catch ex As Exception
            Logger.Error(ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in folder_watch_Created")
        End Try

    End Sub
End Class
