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

 Copyright 2020 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 "CustomLabel.h"

#include <QPainter>
#include <QTextDocument>

void CustomLabel::clear()
{
    pix_    = QPixmap();
    pixOri_ = QPixmap();
    if (doc_) {
        doc_->clear();
    }
    txt_.clear();
    update();
}

void CustomLabel::setPixmap(QPixmap pix)
{
    mode_   = PixmapMode;
    pixOri_ = pix;
    makePix();
    update();
}

void CustomLabel::makePix()
{
    if (pixOri_.isNull()) {
        pix_ = QPixmap();
        return;
    }

    if (width() < pixOri_.width())
        pix_ = pixOri_.scaledToWidth(width(), Qt::SmoothTransformation);
    else
        pix_ = pixOri_;
}

void CustomLabel::setText(QString txt)
{
    mode_ = TextMode;
    txt_  = txt;
    makeDoc();
    doc_->setHtml(txt_);
    update();
}

void CustomLabel::setTextAndPixmap(QString txt, QPixmap pix)
{
    mode_   = TextAndPixmapMode;
    pixOri_ = pix;
    txt_    = txt;
    makeDoc();
    doc_->setHtml(txt_);
    makePix();
    update();
}

void CustomLabel::makeDoc()
{
    if (!doc_) {
        doc_ = new QTextDocument(this);
        QTextOption opt;
        opt.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
        doc_->setDefaultTextOption(opt);
        doc_->setPageSize(size());
    }
}

void CustomLabel::resizeEvent(QResizeEvent*)
{
    if (mode_ == TextMode) {
        if (doc_) {
            doc_->setPageSize(size());
        }
    }
    else if (mode_ == PixmapMode) {
        makePix();
    }
    else {
        if (doc_) {
            doc_->setPageSize(size());
        }
        makePix();
    }
}

void CustomLabel::paintEvent(QPaintEvent*)
{
    QPainter painter(this);

    if (mode_ == TextMode) {
        if (!txt_.isEmpty()) {
            QRect r(0, 0, width(), height());
            doc_->setPageSize(size());
            doc_->drawContents(&painter, r);
        }
    }
    else if (mode_ == PixmapMode) {
        if (!pix_.isNull()) {
            painter.drawPixmap(QPoint(width() / 2 - pix_.width() / 2,
                                      height() / 2 - pix_.height() / 2),
                               pix_);
        }
    }
    else {
        int h = 0;
        if (!txt_.isEmpty()) {
            QRect r(0, 0, width(), height());
            doc_->setPageSize(size());
            doc_->drawContents(&painter, r);
            h = doc_->size().height();
        }
        if (!pix_.isNull()) {
            painter.drawPixmap(QPoint(width() / 2 - pix_.width() / 2, h + 10), pix_);
        }
    }
}
