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

 Copyright 2012 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 "StatusMsgHandler.h"

#include <QDebug>
#include <QLabel>

#include "MvQTheme.h"

StatusMsgHandler* StatusMsgHandler::instance_ = nullptr;

static QColor errorCol;
static QColor okCol;

StatusMsgHandler::StatusMsgHandler()
{
    if (!errorCol.isValid()) {
        errorCol = MvQTheme::colour("status", "error");
        okCol = MvQTheme::colour("status", "ok");
    }
}

StatusMsgHandler* StatusMsgHandler::instance()
{
    if (!instance_) {
        instance_ = new StatusMsgHandler();
    }

    return instance_;
}

void StatusMsgHandler::init(QLabel* label)
{
    label_ = label;
}

void StatusMsgHandler::show(QString s, bool replace)
{
    Q_ASSERT(label_);

    if (!replace && timer_.elapsed() < period_) {
        QString t = label_->text();
        if (!t.isEmpty())
            s = t + "  " + s;
    }

    label_->setText(s);
    label_->repaint();
    timer_.restart();
}

void StatusMsgHandler::failed(QString txt)
{
    Q_ASSERT(label_);
    QString s = txt + " <b><font color=\'" + errorCol.name() + "\'>FAILED</font></b>";
    show(s);
}

void StatusMsgHandler::done(QString txt)
{
    Q_ASSERT(label_);
    QString s = txt + " <b><font color=\'" + okCol.name() + "\'>DONE</font></b>";
    show(s);
}

void StatusMsgHandler::task(QString s)
{
    s += " ...";
    show(s);
}

void StatusMsgHandler::failed()
{
    Q_ASSERT(label_);
    QString s = label_->text();
    if (s.endsWith(" ...")) {
        s.remove(s.size() - 4, 4);
        s += ": <b><font color=\'" + errorCol.name() + "\'>FAILED</font></b>";
        show(s, true);
    }
    else
        clear();
}

void StatusMsgHandler::done()
{
    Q_ASSERT(label_);
    QString s = label_->text();
    if (s.endsWith("...")) {
        s.remove(s.size() - 3, 3);
        s += ": <b><font color=\'" + okCol.name() + "\'>DONE</font></b>";
        show(s, true);
    }
    else
        clear();
}

void StatusMsgHandler::clear()
{
    Q_ASSERT(label_);
    label_->clear();
    timer_ = QElapsedTimer();
}
