Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports Nexamas.UI.Controls
Imports Nexamas.UI.Theming

Namespace Nexamas.UI.Composition

    ''' <summary>
    ''' Internal host-bound presentation gateway for semantic CommandActions overflow.
    ''' Composition owns the overflow decision, while the active host owns how an overflow menu is
    ''' presented. This keeps command rows from leaking outside their slot without making product
    ''' screens wire DropDownMenuPopupService or RootHost directly.
    ''' </summary>
    Friend NotInheritable Class MASCommandActionsOverflowPresenterRegistry

        Friend Delegate Sub OverflowPresenter(anchorControl As MASControlBase,
                                               overflowActions As IReadOnlyList(Of MASControlBase))

        Private Shared ReadOnly _presenters As New Dictionary(Of ThemeHost, OverflowPresenter)()
        Private Shared ReadOnly _syncRoot As New Object()

        Private Sub New()
        End Sub

        Friend Shared Sub Register(host As ThemeHost,
                                   presenter As OverflowPresenter)
            If host Is Nothing OrElse presenter Is Nothing Then Return

            SyncLock _syncRoot
                _presenters(host) = presenter
            End SyncLock
        End Sub

        Friend Shared Sub Unregister(host As ThemeHost)
            If host Is Nothing Then Return

            SyncLock _syncRoot
                If _presenters.ContainsKey(host) Then _presenters.Remove(host)
            End SyncLock
        End Sub

        Friend Shared Function TryPresent(anchorControl As MASControlBase,
                                          overflowActions As IReadOnlyList(Of MASControlBase)) As Boolean
            If anchorControl Is Nothing Then Return False
            If overflowActions Is Nothing OrElse overflowActions.Count = 0 Then Return False

            Dim presenter As OverflowPresenter = Nothing
            Dim host As ThemeHost = anchorControl.Host
            If host Is Nothing Then Return False

            SyncLock _syncRoot
                If Not _presenters.TryGetValue(host, presenter) Then Return False
            End SyncLock

            If presenter Is Nothing Then Return False

            presenter.Invoke(anchorControl, overflowActions)
            Return True
        End Function

    End Class

End Namespace
