Imports System.IO

''' <summary>
''' Built-in filters for FileWatcher that are useful for correctly detecting changes on Office documents (currently Office 2016)
''' </summary>
Public Class FileWatcherFilters
    ''' <summary>
    ''' Base Filter that all filters must inherit from
    ''' Provides two functions that may be overridden and some useful file extension lists
    ''' </summary>
    Public MustInherit Class BaseFileFilter
        Public TempFiles As New List(Of String) From {".tmp", ""}

        Public Overridable Function ShouldFilter(e As FileSystemEventArgs) As Boolean
            Return False
        End Function
        Public Overridable Function ShouldRaiseSave(e As RenamedEventArgs) As Boolean
            Return False
        End Function
    End Class

    ''' <summary>
    ''' Simple Filter that filters changes made on temporary files
    ''' </summary>
    Public Class TempFileFilter
        Inherits BaseFileFilter

        Public Overrides Function ShouldFilter(e As FileSystemEventArgs) As Boolean
            Dim oFileInfo As New FileInfo(e.FullPath)
            Return TempFiles.Contains(oFileInfo.Extension)
        End Function
    End Class

    ''' <summary>
    ''' Filter to detect changes on Office files
    ''' </summary>
    Public Class OfficeFileFilter
        Inherits BaseFileFilter

        Public OfficeFiles As New List(Of String) From {".docx", ".pptx", ".xlsx"}

        Public Overrides Function ShouldFilter(e As FileSystemEventArgs) As Boolean
            Dim oFileInfo As New FileInfo(e.FullPath)
            Return OfficeFiles.Contains(oFileInfo.Extension) And oFileInfo.Name.StartsWith("~")
        End Function

        Public Overrides Function ShouldRaiseSave(e As RenamedEventArgs) As Boolean
            Dim oIsTransform = OfficeFiles.Any(Function(Extension As String)
                                                   Return e.OldName.EndsWith(Extension)
                                               End Function)

            ' Check if it is renamed to a temp file
            Dim oIsTempFile = TempFiles.Any(Function(Extension)
                                                Return e.Name.EndsWith(Extension)
                                            End Function)


            Return oIsTransform And oIsTempFile
        End Function
    End Class
End Class
