/***************************** LICENSE START ***********************************

 Copyright 2022 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "FontMetrics.h"

#include <QImage>
#include <QPainter>
#include "MvQMethods.h"

FontMetrics::FontMetrics(const QFont& font) :
    QFontMetrics(font),
    font_(font),
    realHeight_(height())
{
    computeRealHeight(font);
}

void FontMetrics::computeRealHeight(QFont f)
{
    QFontMetrics fm(f);
    QString txt = "Ayfgl";
    QImage img(MvQ::textWidth(fm, txt) + 6, fm.height(), QImage::Format_ARGB32_Premultiplied);
    img.fill(Qt::white);
    QPainter p(&img);
    p.setPen(Qt::black);
    f.setBold(true);
    p.setFont(f);
    p.drawText(QRect(0, 0, img.width(), img.height()), Qt::AlignCenter, txt);

    int minRow = img.height() + 100;
    int maxRow = -1;
    for (int i = 0; i < img.height(); i++)
        for (int j = 0; j < img.width(); j++) {
            QRgb c = img.pixel(j, i);
            if (qRed(c) != 255 || qGreen(c) != 255 || qBlue(c) != 255) {
                if (i > maxRow)
                    maxRow = i;
                if (i < minRow)
                    minRow = i;
            }
        }

    if (minRow >= 0 && maxRow < img.height()) {
        realHeight_ = maxRow - minRow + 1;
        topPadding_ = minRow;
        bottomPadding_ = img.height() - 1 - maxRow;
    }
}

int FontMetrics::realWidth(QString txt, int& leftPadding, int& rightPadding) const
{
    leftPadding = 0;
    rightPadding = 0;
    QImage img(MvQ::textWidth(*this, txt) + 6, height(), QImage::Format_ARGB32_Premultiplied);
    img.fill(Qt::white);
    QPainter p(&img);
    p.setPen(Qt::black);
    QFont f = font_;
    //    f.setBold(true);
    p.setFont(f);
    p.drawText(QRect(0, 0, img.width(), img.height()), Qt::AlignCenter, txt);

    int minCol = img.width() + 100;
    int maxCol = -1;
    for (int i = 0; i < img.height(); i++)
        for (int j = 0; j < img.width(); j++) {
            QRgb c = img.pixel(j, i);
            if (qRed(c) != 255 || qGreen(c) != 255 || qBlue(c) != 255) {
                if (j > maxCol)
                    maxCol = j;
                if (j < minCol)
                    minCol = j;
            }
        }

    if (minCol >= 0 && maxCol < img.width()) {
        leftPadding = minCol;
        rightPadding = img.width() - 1 - maxCol;
    }
    return maxCol - minCol + 1;
}
