#include <Widget/Layout/Column/Column.hpp>

void Column::layout()
{
    int mainHeight = 0;
    int units = 0;

    for (ChildNode &node : m_children)
    {
        glm::ivec2 childMinSize = node.widget->getMinSize();

        if (node.proportion == 0)
        {
            mainHeight += childMinSize[1];
        }
        else
        {
            units += node.proportion;
        }
    }

    int unitHeight = 0;
    int extraPixels = 0;

    if (units != 0)
    {
        unitHeight = (m_size[1] - mainHeight) / units;
        extraPixels = (m_size[1] - mainHeight) % units;
    }

    glm::ivec2 nextPos(0, 0);

    for (ChildNode &node : m_children)
    {
        int childHeight = node.widget->getMinSize()[1];
        if (node.proportion != 0)
        {
            childHeight = node.proportion * unitHeight;

            int extra = std::min(node.proportion, extraPixels);
            extraPixels -= extra;
            childHeight += extra;
        }

        node.pos = nextPos;
        nextPos[1] += childHeight;

        node.widget->onResize(glm::ivec2(m_size[0], childHeight));
    }
}

glm::ivec2 Column::getMinSize()
{
    int width = 0;
    int height = 0;

    for (ChildNode &node : m_children)
    {
        glm::ivec2 childMinSize = node.widget->getMinSize();
        width = std::max(width, childMinSize[0]);
        height += childMinSize[1];
    }

    return glm::ivec2(width, height);
}