#include <GraphicsContext/GraphicsContext.hpp>
#include <Widget/Layout/PopupContainer/PopupContainer.hpp>

PopupContainer::PopupContainer(glm::ivec2 pos, Widget *content) :
    Layout(content),
    popupPos(pos)
{}

void PopupContainer::layout()
{
    ChildNode &childNode = m_children.back();
    childNode.pos = popupPos + glm::ivec2(1);
    childNode.widget->onResize(childNode.widget->getMinSize());
}

glm::ivec2 PopupContainer::getMinSize()
{
    return m_children.back().widget->getMinSize() + glm::ivec2(2);
}

void PopupContainer::onMouseUp(Uint8 button)
{
    ChildNode &childNode = m_children.back();
    if (button == SDL_BUTTON_LEFT)
    {
        if (!childNode.widget->isMouseInside())
        {
            closePopup();
            return;
        }
    }

    Layout::onMouseUp(button);
}

void PopupContainer::draw(GraphicsContext &context)
{
    if (isMouseInside())
    {
        Widget::setCursor(Material::cursor, glm::ivec2(0));
    }

    ChildNode &childNode = m_children.back();
    glm::ivec2 fullSize = childNode.widget->getCurrentSize() + glm::ivec2(2);

    context.color = glm::vec4(1.0f);
    context.drawRect(childNode.pos.x - 1, childNode.pos.y - 1, fullSize.x, fullSize.y);
    context.color = Color::popupBackground;
    context.drawRect(childNode.pos.x, childNode.pos.y, fullSize.x - 2, fullSize.y - 2);

    Layout::draw(context);
}