Option Strict On
Option Explicit On

Imports System.Collections.Generic

Namespace Nexamas.UI.Rendering

    Friend NotInheritable Class MessageBoxButtonLayoutPlanner

        Private Sub New()
        End Sub

        Friend Shared Function ArrangeRowsByWidths(buttonWidths As IReadOnlyList(Of Single),
                                                   availableWidth As Single,
                                                   columnGap As Single) As List(Of List(Of Integer))

            Dim rows As New List(Of List(Of Integer))()

            If buttonWidths Is Nothing OrElse buttonWidths.Count = 0 Then
                Return rows
            End If

            Dim currentRow As New List(Of Integer)()
            Dim currentWidth As Single = 0.0F

            For i As Integer = 0 To buttonWidths.Count - 1
                Dim bw As Single = buttonWidths(i)
                Dim needed As Single = bw

                If currentRow.Count > 0 Then
                    needed += columnGap
                End If

                If currentRow.Count > 0 AndAlso (currentWidth + needed) > availableWidth Then
                    rows.Add(currentRow)
                    currentRow = New List(Of Integer)()
                    currentWidth = 0.0F
                End If

                If currentRow.Count > 0 Then
                    currentWidth += columnGap
                End If

                currentRow.Add(i)
                currentWidth += bw
            Next

            If currentRow.Count > 0 Then
                rows.Add(currentRow)
            End If

            Return rows
        End Function

        Friend Shared Function ComputeMaxRowWidth(buttonWidths As IReadOnlyList(Of Single),
                                                  rows As IReadOnlyList(Of List(Of Integer)),
                                                  columnGap As Single) As Single

            If buttonWidths Is Nothing OrElse rows Is Nothing OrElse rows.Count = 0 Then
                Return 0.0F
            End If

            Dim maxWidth As Single = 0.0F

            For Each row As List(Of Integer) In rows
                Dim rowWidth As Single = 0.0F

                If row IsNot Nothing Then
                    For i As Integer = 0 To row.Count - 1
                        rowWidth += buttonWidths(row(i))
                    Next

                    rowWidth += Math.Max(0, row.Count - 1) * columnGap
                End If

                If rowWidth > maxWidth Then
                    maxWidth = rowWidth
                End If
            Next

            Return maxWidth
        End Function

    End Class

End Namespace