#include "IconCaption.h"

#include <QFontMetrics>
#include <QGuiApplication>
#include <QPainter>
#include <QRect>

QPixmap renderCaptionWithIcon(const QString& text, const QPixmap& icon,
                              const QFont& font, const QColor& textColor)
{
    const QFontMetrics metrics(font);
    const int textWidth = metrics.horizontalAdvance(text);
    const int gap = icon.isNull() ? 0 : 6;

    // The icon is drawn at the caption's device-independent pixel size; the source
    // pixmap may be larger (rasterized at a target size / device pixel ratio), so
    // divide by its own dpr to get its logical size.
    const qreal iconDpr = icon.isNull() ? 1.0 : icon.devicePixelRatio();
    const int iconW = icon.isNull() ? 0
        : static_cast<int>(icon.width()  / iconDpr);
    const int iconH = icon.isNull() ? 0
        : static_cast<int>(icon.height() / iconDpr);

    const int width  = textWidth + gap + iconW;
    const int height = qMax(metrics.height(), iconH);

    const qreal dpr = qApp ? qApp->devicePixelRatio() : 1.0;
    QPixmap pixmap(static_cast<int>(width * dpr), static_cast<int>(height * dpr));
    pixmap.setDevicePixelRatio(dpr);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
    painter.setFont(font);
    painter.setPen(textColor);
    painter.drawText(QRect(0, 0, textWidth, height),
                     Qt::AlignLeft | Qt::AlignVCenter, text);

    if (!icon.isNull())
    {
        const int iconX = textWidth + gap;
        const int iconY = (height - iconH) / 2;
        painter.drawPixmap(QRect(iconX, iconY, iconW, iconH), icon);
    }

    return pixmap;
}

QSize getLogicalSize(const QPixmap& pixmap)
{
    if (pixmap.isNull()) { return QSize(0, 0); }
    const qreal dpr = pixmap.devicePixelRatio();
    return QSize(static_cast<int>(pixmap.width()  / dpr),
                 static_cast<int>(pixmap.height() / dpr));
}
