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

void Row::layout()
{
    int mainWidth = 0;
    int units = 0;

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

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

    int unitWidth = 0;
    int extraPixels = 0;

    if (units != 0)
    {
        unitWidth = (m_size[0] - mainWidth) / units;
        extraPixels = (m_size[0] - mainWidth) % units;
    }

    glm::ivec2 nextPos(0, 0);

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

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

        node.pos = nextPos;
        nextPos[0] += childWidth;

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

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

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

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