Option Strict On
Option Explicit On

Imports System.Collections.Generic
Imports System.Threading

Namespace Nexamas.UI.FileSystem

    Friend NotInheritable Class FileSystemEntryChildrenLoader

        Private ReadOnly _provider As IFileSystemProvider

        Friend Sub New()
            Me.New(New LocalFileSystemProvider())
        End Sub

        Friend Sub New(provider As IFileSystemProvider)
            _provider = If(provider, New LocalFileSystemProvider())
        End Sub

        Friend Function GetChildren(entry As FileSystemEntry,
                                    Optional showHidden As Boolean = False) As List(Of FileSystemEntry)

            Return GetChildren(entry, showHidden, CancellationToken.None)
        End Function

        Friend Function GetChildren(entry As FileSystemEntry,
                                    showHidden As Boolean,
                                    cancellationToken As CancellationToken) As List(Of FileSystemEntry)

            Dim result As New List(Of FileSystemEntry)()

            If entry Is Nothing Then Return result
            If Not entry.IsFolderLike Then Return result
            If String.IsNullOrWhiteSpace(entry.FullPath) Then Return result

            Dim children As List(Of FileSystemEntry)

            Try
                cancellationToken.ThrowIfCancellationRequested()

                Dim cancellable As IFileSystemCancellableProvider = TryCast(_provider, IFileSystemCancellableProvider)

                If cancellable IsNot Nothing Then
                    children = cancellable.GetChildren(entry.FullPath, cancellationToken)
                Else
                    children = _provider.GetChildren(entry.FullPath)
                End If

                cancellationToken.ThrowIfCancellationRequested()
            Catch masCanceled1 As OperationCanceledException
                Throw
            Catch masCaughtException1 As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowFileSystemBoundary(masCaughtException1)
                Return result
            End Try

            If children Is Nothing Then Return result

            For Each child As FileSystemEntry In children
                cancellationToken.ThrowIfCancellationRequested()

                If child Is Nothing Then Continue For
                If Not showHidden AndAlso child.IsHidden Then Continue For
                result.Add(child)
            Next

            Return result
        End Function

    End Class

End Namespace