Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports Nexamas.UI.Components
Imports Nexamas.UI.Controls
Imports Nexamas.UI.Host
Imports Nexamas.UI.Layout
Imports Nexamas.UI.Theming
Imports SkiaSharp

Namespace Nexamas.UI.Application

    Partial Public NotInheritable Class MASApplicationWindowControls

        ''' <summary>
        ''' Applies an official MASSize/MASLayout page plan to direct MAS controls hosted by this window.
        ''' This is the beginner-facing replacement for normal consumer x/y/w/h math in external product and sample pages.
        ''' The build action is retained and reapplied when the host surface is measured again, so resize uses the
        ''' same page intent instead of stale manual bounds.
        ''' </summary>
        Public Function LayoutPage(buildAction As Action(Of MASApplicationLayoutPageBuilder)) As Boolean
            Return LayoutPageInternal(buildAction, fixedSizeProfile:=Nothing)
        End Function


        Public Function LayoutPage(buildAction As Action(Of MASApplicationLayoutPageBuilder),
                                   density As MASControlDensity) As Boolean
            Return LayoutPageInternal(buildAction, MASSizeProfile.FromDensity(density))
        End Function


        Public Function LayoutPage(buildAction As Action(Of MASApplicationLayoutPageBuilder),
                                   sizeProfile As MASSizeProfile) As Boolean
            Return LayoutPageInternal(buildAction, MASSizeProfile.Normalize(sizeProfile))
        End Function


        Private Function LayoutPageInternal(buildAction As Action(Of MASApplicationLayoutPageBuilder),
                                            fixedSizeProfile As MASSizeProfile) As Boolean
            If buildAction Is Nothing Then Throw New ArgumentNullException(NameOf(buildAction))

            Return ExecuteControlsUiThread(
                "LayoutPage",
                Function()
                    Dim nextSession As New MASApplicationControlsLayoutSession(_rootHost, Me, buildAction, fixedSizeProfile)
                    Dim applied As Boolean = False

                    Try
                        applied = nextSession.ApplyNow()
                    Catch masCaughtException1 As Exception
                        nextSession.Dispose()
                        Throw
                    End Try

                    If ShouldRetainExistingLayoutSessionAfterFailedApply(applied) Then
                        nextSession.Dispose()
                        Return False
                    End If

                    ClearRetainedLayoutSessionsInternal()
                    _layoutPageSession = nextSession
                    Return True
                End Function)
        End Function
    End Class

End Namespace
