Option Strict On
Option Explicit On

Imports System
Imports Nexamas.UI.Components
Imports Nexamas.UI.Theming
Imports SkiaSharp
Imports Nexamas.UI.Controls
Namespace Nexamas.UI.Verification

    ''' <summary>
    ''' Single deterministic host used to capture Render Verification scenarios into bitmaps.
    ''' </summary>
    ''' <remarks>
    ''' This host centralizes bitmap allocation, canvas lifetime, DPI/theme resolution, ControlsLayer creation,
    ''' ThemeHost binding, and after-layer rendering. Product-specific capture classes only register scene content;
    ''' they do not own ad-hoc ThemeHost or ControlsLayer construction paths.
    ''' </remarks>
    Friend NotInheritable Class MASRenderVerificationCaptureHost
        Private Sub New()
        End Sub

        ''' <summary>
        ''' Captures a scenario using a deterministic Nexamas UI ThemeHost/ControlsLayer context.
        ''' </summary>
        Friend Shared Function Capture(scenario As MASRenderVerificationScenario,
                                       backgroundColor As SKColor,
                                       buildScene As Action(Of MASRenderVerificationCaptureContext)) As SKBitmap
            If scenario Is Nothing Then Throw New ArgumentNullException(NameOf(scenario))
            If buildScene Is Nothing Then Throw New ArgumentNullException(NameOf(buildScene))

            Dim bitmap As New SKBitmap(scenario.WidthPx, scenario.HeightPx)
            Dim canvas As New SKCanvas(bitmap)
            Dim themeHost As New ThemeHost()
            Dim layer As New ControlsLayer(Sub()
                                           End Sub)

            Dim context As MASRenderVerificationCaptureContext = Nothing
            Try
                themeHost.EnsureWithResolvedTheme(scenario.DpiScale, MASRenderVerificationThemeResolver.Resolve(scenario.ThemeKey))
                layer.SetHost(themeHost)
                context = New MASRenderVerificationCaptureContext(scenario, bitmap, canvas, themeHost, layer)
                context.Canvas.Clear(backgroundColor)

                buildScene(context)
                context.RenderLayerAndAfterLayer()

                Return context.DetachBitmap()
            Finally
                If context IsNot Nothing Then
                    context.Dispose()
                Else
                    layer.Dispose()
                    canvas.Dispose()
                    themeHost.Dispose()
                    bitmap.Dispose()
                End If
            End Try
        End Function
    End Class

End Namespace
