#include "BigLabel.h"
#include <iostream>

#include <QFont>
#include <QLabel>
#include <QResizeEvent>
#include <QSettings>
#include <QWidget>

#include "QuantityFormat.h"
#include "TDeviceManager.h"
#include "chip.h"

BigLabel::BigLabel() {
    setText("...");
    setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
}

BigLabel::~BigLabel() {}

void BigLabel::refresh(const TChannel *channel) {
    QSettings settings;
    QString final_text;

    bool showAliases = settings.value("bigview/show_aliases").toBool();
    const Quantity &qty = channel->calibratedQuantity;

    if (qty.type == QUANTITY_TYPE_ERROR) {

        if (showAliases) {
            const QString &alias = TDeviceManager::instance().getAlias(channel->id);
            final_text += alias;
            final_text += ": (error)";
        }

        final_text += chip_error_to_string(qty.value_error);
    } else {
        QString d = QuantityFormat::instance().toString(qty);

        if (showAliases) {
            const QString &alias = TDeviceManager::instance().getAlias(channel->id);
            final_text += alias;
            final_text += ": ";
        }

        final_text += d;

        if (settings.value("bigview/show_units").toBool()) {
            final_text += " ";
            final_text += QString::fromUtf8(unit_to_string(qty.unit, 0));
        }
    }

    setText(final_text);
    fitFont(rect()); // fix the font size
}

void BigLabel::fitFont(QRect rect) {
    int flags = Qt::TextDontClip;
    QFont f = font();

    // Step 1: Try to set the requested height. If everything fits horizontally,
    // all labels will have equal height.
    f = font();
    double orig = rect.size().height() * 0.8;
    f.setPixelSize(orig);

    // Step 2: Long strings may be cut. If this happens,
    // reduce the font until it fits in the target width.
    QRect fontBoundRect = QFontMetrics(f).boundingRect(rect, flags, text());

    //	qDebug() << "font width: " << fontBoundRect.width() << " space:" << resize.width() << " Text: " << text();

    while (fontBoundRect.width() > rect.size().width() && orig > 0) {

        f.setPixelSize(orig);
        orig -= (orig * 0.1); // 10% decrements. Every resize then requires approx. 10 iterations

        //		qDebug() << "Testing size: " << orig;

        fontBoundRect = QFontMetrics(f).boundingRect(rect, flags, text());
    }

    setFont(f);
}

void BigLabel::resizeEvent(QResizeEvent *event) {
    QRect resize(0, 0, event->size().width(), event->size().height());
    fitFont(resize);
    QFrame::resizeEvent(event);
}
