using System.Numerics;
using Voile.Rendering;

namespace Voile.UI.Containers;

/// <summary>
/// A grid container arranges its children in a grid layout with a given column count, and column and row spacing between child elements.
/// </summary>
public class GridContainer : Container
{
    /// <summary>
    /// Amount of columns this grid has.
    /// </summary>
    public int Columns { get; set; } = 2;
    /// <summary>
    /// Spacing between each grid column.
    /// </summary>
    public float ColumnSpacing { get; set; } = 16.0f;
    /// <summary>
    /// Spacing between each grid row.
    /// </summary>
    public float RowSpacing { get; set; } = 16.0f;

    public GridContainer(Rect minimumSize, List<UIElement> children, int columns = 2, float colSpacing = 16.0f, float rowSpacing = 16.0f)
        : base(minimumSize, children)
    {
        Columns = columns;
        ColumnSpacing = colSpacing;
        RowSpacing = rowSpacing;
    }

    public GridContainer(int columns = 2, float colSpacing = 16.0f, float rowSpacing = 16.0f)
    {
        Columns = columns;
        ColumnSpacing = colSpacing;
        RowSpacing = rowSpacing;
    }

    public override void Arrange()
    {
        float currentX = 0.0f;
        float currentY = 0.0f;
        int colIndex = 0;

        foreach (var child in Children)
        {
            child.LocalPosition = new Vector2(currentX, currentY);

            float childWidth = 0.0f;
            float childHeight = 0.0f;

            childWidth = child.Size.Width;
            childHeight = child.Size.Height;

            colIndex++;

            if (colIndex >= Columns)
            {
                colIndex = 0;
                currentX = 0.0f;
                currentY += childHeight + RowSpacing;
            }
            else
            {
                currentX += childWidth + ColumnSpacing;
            }
        }
    }
}