#include <ToolTip/ToolTip.hpp>
#include <Widget/Button/Button.hpp>
#include <Widget/ItemFilterDropdown/ItemFilterDropdown.hpp>
#include <Widget/Layout/Column/Column.hpp>
#include <Widget/Layout/CompoundWidget/ItemPicker/ItemPicker.hpp>

ItemFilterDropdown::ItemFilterDropdown(ItemStack &selection, ChangedCallback onChanged) :
    selection(selection),
    onChanged(onChanged)
{}

void ItemFilterDropdown::draw(GraphicsContext &context)
{
    if (shouldClosePopup)
    {
        closePopup();
        shouldClosePopup = false;
    }

    if (isHostingPopup())
    {
        context.color = glm::vec4(1.0f);
    }
    else if (isMouseInside())
    {
        context.color = Color::selection;
    }
    else
    {
        context.color = Color::widgetBackground;
    }

    context.drawRect(0, 0, m_size.x, m_size.y);

    if (selection.isEmpty())
    {
        context.color = Color::faded;
        context.drawText(Font::generic, 4, 3, "*");

        if (isMouseInside())
        {
            ToolTip &tip = context.createToolTip();
            tip.addLine(Color::faded, "(Any item)");
        }
    }
    else
    {
        selection.getItem()->draw(context, 2, 2, selection);

        if (isMouseInside())
        {
            ToolTip &tip = context.createToolTip();
            tip.addLine(glm::vec4(1.0f), selection.getDisplayName());
        }
    }
}

glm::ivec2 ItemFilterDropdown::getMinSize()
{
    return glm::ivec2(12, 12);
}

void ItemFilterDropdown::onMouseUp(Uint8 button)
{
    if (button == SDL_BUTTON_LEFT && isMouseInside())
    {
        openPopup(
            glm::ivec2(0, m_size.y),
            new Column(
                new Button(
                    "(Any item)",
                    [this]()
                    {
                        selection = ItemStack();
                        shouldClosePopup = true;
                        onChanged();
                    }
                ),

                Layout::WithProportion<1>(),
                new ItemPicker(
                    [this](ItemStack stack)
                    {
                        selection = stack;
                        shouldClosePopup = true;
                        onChanged();
                    }
                )
            )
        );

        return;
    }

    Widget::onMouseUp(button);
}