#include <Widget/Layout/Layout.hpp>

Layout::~Layout()
{
    for (ChildNode &node : m_children)
    {
        delete node.widget;
    }
}

void Layout::onResize(glm::ivec2 newSize)
{
    Widget::onResize(newSize);
    layout();
}

void Layout::draw(GraphicsContext &context)
{
    for (ChildNode &node : m_children)
    {
        context.pushViewport();
        context.clipViewport(node.pos, node.widget->getCurrentSize());
        node.widget->widgetAbsPos = context.getAbsPos(glm::ivec2(0));
        node.widget->draw(context);
        context.popViewport();
    }
}

void Layout::onMouseMoved(glm::ivec2 pos)
{
    Widget::onMouseMoved(pos);

    for (ChildNode &node : m_children)
    {
        node.widget->onMouseMoved(pos - node.pos);
    }
}

void Layout::onMouseUp(Uint8 button)
{
    for (ChildNode &node : m_children)
    {
        node.widget->onMouseUp(button);
    }
}

void Layout::onMouseDown(Uint8 button)
{
    bool insideAnyWidget = false;
    for (ChildNode &node : m_children)
    {
        insideAnyWidget = insideAnyWidget || node.widget->isMouseInside();
        node.widget->onMouseDown(button);
    }

    if (!insideAnyWidget)
    {
        Widget::onMouseDown(button);
    }
}

void Layout::onScroll(int delta)
{
    for (ChildNode &node : m_children)
    {
        node.widget->onScroll(delta);
    }
}

void Layout::getInternalTabOrder(std::vector<Widget*> &tabOrder)
{
    for (ChildNode &node : m_children)
    {
        node.widget->getInternalTabOrder(tabOrder);
    }
}