Option Strict On
Option Explicit On

Imports System
Imports Nexamas.UI.Layout
Imports Nexamas.UI.Theming
Imports Nexamas.UI.Values
Imports SkiaSharp

Namespace Nexamas.UI.Components

    Friend NotInheritable Class MASPropertyGridLayoutPlan
        Friend Shared ReadOnly Thresholds As New MASResponsiveLayoutThresholds(
            fullWidthDip:=MASPropertyGridTokens.DesiredSizeDip.Width,
            denseWidthDip:=320.0F,
            compactWidthDip:=MASPropertyGridTokens.MinimumSizeDip.Width,
            minimalWidthDip:=150.0F,
            fullHeightDip:=MASPropertyGridTokens.DesiredSizeDip.Height,
            denseHeightDip:=300.0F,
            compactHeightDip:=MASPropertyGridTokens.MinimumSizeDip.Height,
            minimalHeightDip:=96.0F)

        Friend ReadOnly Property ResponsiveProfile As MASResponsiveLayoutProfile
        Friend ReadOnly Property PixelDpi As Single
        Friend ReadOnly Property MetricDpi As Single
        Friend ReadOnly Property GridRectPx As SKRect

        Private Sub New(profile As MASResponsiveLayoutProfile,
                        metricDpi As Single,
                        gridRectPx As SKRect)
            Dim safeProfile As MASResponsiveLayoutProfile = If(profile, MASResponsiveLayoutResolver.FromLogicalSize(MASSizeLayoutIntegrationContext.Empty, SKSize.Empty, MASSize.Default, Thresholds))
            Me.ResponsiveProfile = safeProfile
            Me.PixelDpi = safeProfile.DpiScale
            Me.MetricDpi = Math.Max(0.25F, metricDpi)
            Me.GridRectPx = SanitizeRect(gridRectPx)
        End Sub

        Friend Shared Function Create(ctx As MASThemeContext,
                                      boundsPx As SKRect,
                                      sizeIntent As MASSize) As MASPropertyGridLayoutPlan
            Dim profile As MASResponsiveLayoutProfile = MASResponsiveLayoutResolver.FromTheme(ctx, boundsPx, sizeIntent, Thresholds)
            Dim metricDpi As Single = profile.DpiScale * ClampScale((profile.ChromeScale + profile.ContentScale) * 0.5F, 0.64F, 1.2F)

            Dim gridRect As SKRect = MASPropertyGridTokens.ResolveGridRect(boundsPx, metricDpi)
            If profile.IsCollapsed OrElse gridRect.Width <= 1.0F OrElse gridRect.Height <= 1.0F Then
                gridRect = SKRect.Empty
            End If

            Return New MASPropertyGridLayoutPlan(profile, metricDpi, gridRect)
        End Function

        Private Shared Function ClampScale(value As Single, minValue As Single, maxValue As Single) As Single
            If Single.IsNaN(value) OrElse Single.IsInfinity(value) OrElse value <= 0.0F Then Return 1.0F
            Return Math.Max(minValue, Math.Min(maxValue, value))
        End Function

        Private Shared Function SanitizeRect(rect As SKRect) As SKRect
            If rect.IsEmpty OrElse rect.Width <= 1.0F OrElse rect.Height <= 1.0F Then Return SKRect.Empty
            Return rect
        End Function
    End Class

End Namespace
