#include <ToolTip/ToolTip.hpp>
#include <Color/Color.hpp>

ToolTip::Line::Line(glm::vec4 color, std::string text) : color(color), text(text) {}

void ToolTip::addLine(glm::vec4 color, std::string text)
{
    // Check for newline.
    size_t newLineIndex = text.find('\n');
    size_t oldLineIndex = 0;
    while (newLineIndex != std::string::npos)
    {
        // Add the text before the newline, also dont add any text thats already been added.
        m_lines.push_back(Line(color, text.substr(oldLineIndex, newLineIndex - ((oldLineIndex == 0) ? oldLineIndex : oldLineIndex - 1))));
        oldLineIndex = newLineIndex + 1;
        // Find the next newline in the remaining text.
        newLineIndex = text.find('\n', oldLineIndex);
    }

    // Add the last line of text.
    m_lines.push_back(Line(color, text.substr(oldLineIndex)));
}

void ToolTip::addLine(std::string text)
{
    addLine(Color::faded, text);
}

void ToolTip::draw(GraphicsContext &context, int x, int y)
{
    if (m_lines.size() == 0)
    {
        return;
    }
    
    int longestLine = 0;
    for (Line &line : m_lines)
    {
        int thisLineWidth = context.measureText(Font::generic, line.text)[0];
        if (thisLineWidth > longestLine)
        {
            longestLine = thisLineWidth;
        }
    }

    int totalWidth = longestLine + 4;
    int totalHeight = (Font::generic.glyphHeight + 1) * m_lines.size() + 3;

    context.color = Color::faded;
    context.drawRect(x, y, totalWidth, 1);
    context.drawRect(x, y, 1, totalHeight);
    context.drawRect(x+totalWidth-1, y, 1, totalHeight);
    context.drawRect(x, y+totalHeight-1, totalWidth, 1);
    context.color = glm::vec4(0.0f, 0.0f, 0.0f, 0.95f);
    context.drawRect(x+1, y+1, totalWidth-2, totalHeight-2);

    int plotY = y + 2;
    for (Line &line : m_lines)
    {
        context.color = line.color;
        context.drawText(Font::generic, x+2, plotY, line.text);
        plotY += Font::generic.glyphHeight + 1;
    }
}