Option Strict On
Option Explicit On

Imports System
Imports Nexamas.UI.General
Imports Nexamas.UI.Theming
Imports SkiaSharp

Namespace Nexamas.UI.Components

    Friend NotInheritable Class BackgroundThemeSupport

        Private Sub New()
        End Sub

        Friend Structure BgPalette
            Friend BaseBg As SKColor
            Friend ColdTint As SKColor
            Friend WashBase As SKColor
            Friend VignetteBase As SKColor
        End Structure

        Friend Shared Function ResolveBackgroundTheme(ctx As MASThemeContext) As IMASBackgroundTheme
            If ctx Is Nothing Then Throw New ArgumentNullException(NameOf(ctx))
            If ctx.Theme Is Nothing Then Throw New InvalidOperationException("ThemeContext.Theme is Nothing.")
            If MASAppThemeContracts.Foundation(ctx.Theme).Background Is Nothing Then Throw New InvalidOperationException("Current app theme does not provide Background theme.")
            Return MASAppThemeContracts.Foundation(ctx.Theme).Background
        End Function

        Friend Shared Function GetPalette(ctx As MASThemeContext,
                                          palette As MASBackgroundPalette) As BgPalette

            Dim bg As IMASBackgroundTheme = ResolveBackgroundTheme(ctx)

            Dim src As IMASBackgroundPaletteTheme =
                If(palette = MASBackgroundPalette.Secondary,
                   bg.Secondary,
                   bg.Default)

            Return New BgPalette With {
                .BaseBg = src.BaseBg,
                .ColdTint = src.ColdTint,
                .WashBase = src.WashBase,
                .VignetteBase = src.VignetteBase
            }
        End Function

        Friend Shared Function Clamp01(v As Single) As Single
            If Single.IsNaN(v) OrElse Single.IsInfinity(v) Then Return 0.0F
            If v < 0.0F Then Return 0.0F
            If v > 1.0F Then Return 1.0F
            Return v
        End Function

        Friend Shared Function NearlyEqual(a As Single,
                                           b As Single,
                                           Optional eps As Single = 0.0001F) As Boolean
            If Single.IsNaN(a) OrElse Single.IsNaN(b) Then Return False
            Return Math.Abs(a - b) <= eps
        End Function

    End Class

End Namespace