Imports System.IO
Imports DigitalData.GUIs.Common
Imports DigitalData.Modules.Base
Imports DigitalData.Modules.Logging

Public Class ClassFolderwatcher
    Inherits 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
        If Directory.Exists(My.Application.Globix.CurrentFolderWatchPath) Then
            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
        Else
            Logger.Info($"Attention: Check the fodlerwatchinit-Module...My.Application.Globix.CurrentFolderWatchPath is not existing [{My.Application.Globix.CurrentFolderWatchPath}]")
            Return False
        End If

    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 Function StartStop_FolderWatch()
        Try
            If FWFolderWatcher Is Nothing Then 'OrElse FWFolderWatcher.EnableRaisingEvents = False
                ' Folderwatch neu instanzieren
                FWFolderWatcher = StartFolderwatcherForPath(My.Application.Globix.CurrentFolderWatchPath)
                My.Application.Globix.Folderwatchstarted = True
                My.UIConfig.Globix.FolderWatchStarted = True
                My.UIConfigManager.Save()
                Logger.Info("Folderwatch successfully started!")
                Return 1
            End If

            If FWFolderWatcher.EnableRaisingEvents = True Then
                'Gestartet also Stoppen
                FWFolderWatcher.EnableRaisingEvents = False
                My.Application.Globix.Folderwatchstarted = False
                Logger.Info("Folderwatch stopped!")
                My.UIConfig.Globix.FolderWatchStarted = False
                My.UIConfigManager.Save()
                Return 0
            End If
        Catch ex As Exception
            Logger.Error(ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Folder Watch")

        End Try
    End Function
    Public Function StartStop_FolderWatchSCAN() As Integer
        Try
            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
        Logger.Debug("Folder Watcher starting up for Path [{0}]", pPath)
        Dim oWatcher = New FileSystemWatcher(pPath, "*.*") With {
            .IncludeSubdirectories = False,
            .EnableRaisingEvents = True
        }
        AddHandler oWatcher.Created, AddressOf OnCreated
        Logger.Debug("Folder Watcher started for Path [{0}]", pPath)
        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.Decide_FileHandle(e.FullPath, handleType) = True Then
                My.Application.Globix.NEW_FILES = True
            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
