#include <ItemStack/ItemStack.hpp>
#include <Widget/StaticItemSlot/StaticItemSlot.hpp>
#include <Controller/InventoryController/InventoryController.hpp>
#include <cmath>

glm::vec4 StaticItemSlot::getHighlight()
{
    return staticHighlight;
}

void StaticItemSlot::getExtraToolTipLines(ToolTip &tip)
{
    // NOP
}

void StaticItemSlot::onHoveringOverEmpty(GraphicsContext &context)
{
    if (!emptyToolTip.empty())
    {
        ToolTip &tip = context.createToolTip();
        tip.addLine(emptyToolTip);
    }
}

StaticItemSlot::StaticItemSlot(std::function<ItemStack()> getStack) : m_getStack(getStack) {}

StaticItemSlot::~StaticItemSlot()
{
    if (shared->hoveredSlot == this)
    {
        shared->hoveredSlot = nullptr;
    }
}

StaticItemSlot* StaticItemSlot::withEmptyToolTip(std::string tip)
{
    emptyToolTip = tip;
    return this;
}

StaticItemSlot* StaticItemSlot::withStaticHighlight(glm::vec4 staticHighlight)
{
    this->staticHighlight = staticHighlight;
    return this;
}

void StaticItemSlot::draw(GraphicsContext &context)
{
    context.color = highlightLerp.sample(getHighlight()) + glm::vec4(
        glm::vec3(0.02 * std::sin((float) SDL_GetTicks() / 3000.0f)), 
        0.0f
    );
    context.drawRect(3, 6, 14, 14);

    ItemStack stack = m_getStack();

    glm::vec4 targetBackground;
    if (isMouseInside())
    {
        targetBackground = Color::selection;
    }
    else
    {
        targetBackground = Color::widgetBackground;

        if (shared->hoveredSlot != nullptr)
        {
            ItemStack hoveredStack = shared->hoveredSlot->m_getStack();
            if (!hoveredStack.isEmpty() && hoveredStack.canMergeFrom(stack))
            {
                targetBackground = Color::secondarySelection;
            }
        }
    }

    glm::vec4 baseColor = backgroundLerp.sample(targetBackground);

    context.color = baseColor;
    context.drawRect(4, 7, 12, 12);

    context.color = Color::shade(baseColor);
    context.drawRect(4, 7, 11, 1);
    context.drawRect(4, 8, 1, 10);

    context.color = Color::tint(baseColor);
    context.drawRect(4, 18, 12, 1);
    context.drawRect(15, 7, 1, 11);

    stack.draw(context, 6, 9);

    if (isMouseInside())
    {
        if (!stack.isEmpty())
        {
            ToolTip &tip = context.createToolTip();
            tip.addLine(glm::vec4(1.0f), stack.getDisplayName());
            stack.getExtraToolTipLines(tip);
            getExtraToolTipLines(tip);
        }
        else
        {
            onHoveringOverEmpty(context);
        }
    }
}

glm::ivec2 StaticItemSlot::getMinSize()
{
    return glm::ivec2(20, 21);
}

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

    if (isMouseInside())
    {
        shared->hoveredSlot = this;
    }
    else if (shared->hoveredSlot == this)
    {
        shared->hoveredSlot = nullptr;
    }
}