Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports Nexamas.UI.Components
Imports Nexamas.UI.FloatRuntime
Imports Nexamas.UI.Host
Imports Nexamas.UI.Layout
Imports SkiaSharp

Namespace Nexamas.UI.Application

    Partial Friend NotInheritable Class MASFileExplorerService

#Region "Bounds"

        Friend Function GetDefaultExplorerBoundsPx() As SKRect
            Dim viewportPx As SKRect = _rootHost.GetSurfaceViewportPx()
            Return GetDefaultExplorerBoundsPx(viewportPx)
        End Function

        Friend Function GetDefaultExplorerBoundsPx(availableBoundsPx As SKRect) As SKRect
            If Not IsUsableRect(availableBoundsPx) Then
                Return SKRect.Empty
            End If

            Dim dpi As Single = SafeDpi(_rootHost.GetDpi())

            Dim resolvedBySizeLayout As SKRect =
                MASFloatSurfaceSizeResolver.ResolveCenteredBoundsPixel(
                    kind:=MASFloatSurfaceKind.FileExplorer,
                    availableBoundsPx:=availableBoundsPx,
                    dpiScale:=dpi,
                    intent:=MASSize.Default)

            If IsUsableRect(resolvedBySizeLayout) Then
                Return resolvedBySizeLayout
            End If

            Return availableBoundsPx
        End Function

        Private Function ResolveInitialBoundsPx(boundsPx As SKRect) As SKRect
            If IsUsableRect(boundsPx) Then
                Return boundsPx
            End If

            Return GetDefaultExplorerBoundsPx()
        End Function

        Private Shared Function IsUsableRect(rect As SKRect) As Boolean
            Return Not rect.IsEmpty AndAlso rect.Width > 1.0F AndAlso rect.Height > 1.0F
        End Function

        Private Shared Function SafeDpi(value As Single) As Single
            If value <= 0.0F OrElse Single.IsNaN(value) OrElse Single.IsInfinity(value) Then
                Return 1.0F
            End If

            Return value
        End Function

#End Region

    End Class

End Namespace
