/***************************** 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 <QDebug>
#include <QPalette>

#include "LogHandler.h"
#include "MvQLogBrowser.h"
#include "MvQTheme.h"

static QColor okBg;
static QColor titleFg;
static QColor errorFg;

QMap<QString, QString> MvQLogBrowser::keys_;

MvQLogBrowser::MvQLogBrowser(QWidget* parent) :
    QTextBrowser(parent),
    hasOutput_(false)
{
    setProperty("mvStyle", "log");

    if (!okBg.isValid()) {
        okBg = MvQTheme::colour("log", "ok_bg");
        titleFg = MvQTheme::colour("log", "title");
        errorFg = MvQTheme::colour("log", "error");
    }

    if (keys_.isEmpty()) {
        keys_[QString::fromStdString(GuiLog::commandKey())] = "Command";
        keys_[QString::fromStdString(GuiLog::methodKey())] = "Method";
        keys_[QString::fromStdString(GuiLog::requestKey())] = "Request";
    }

    OutputToGui::setObserver(this);
    // Set css for the text formatting
    QString cssDoc = "table {margin-top: 1px; margin-bottom: 1px; background-color: " + okBg.name() +
                     ";}  \
        td {padding-left: 4px; padding-top: 2px; padding-bottom: 2px;} div {width: 50px; background-color: " +
                     okBg.name() + ";}";
    document()->setDefaultStyleSheet(cssDoc);

    connect(this, SIGNAL(textChanged()),
            this, SLOT(slotTextChanged()));
}

MvQLogBrowser::~MvQLogBrowser() = default;

void MvQLogBrowser::update(const std::string& s, metview::Type t)
{
    if (s.empty())
        return;

    QString txt = QString::fromStdString(s);

    if (t == metview::TaskType) {
        hasOutput_ = false;

        QString desc, cmd, cmdTitle;
        parseTask(txt, desc, cmd, cmdTitle);

        txt = creTitle("Task") + desc;
        if (!cmd.isEmpty()) {
            txt += "<br>" + creTitle(cmdTitle) + cmd;
        }

        if (!document()->isEmpty())
            txt = "<hr>" + txt;
    }
    else if (t == metview::ErrorType) {
        QString p;
        if (!hasOutput_) {
            p = "<br>" + creTitle("Output") + " ";
            hasOutput_ = true;
        }
        txt = p + "<br><font color=\'" + errorFg.name() +
              "\'> <b>ERROR</b> - " + txt + "</font>";
    }
    else {
        QString p;
        if (!hasOutput_) {
            p = creTitle("Output") + " ";
            hasOutput_ = true;
        }

        txt += "<br>" + p + QString::fromStdString(s);
    }

    moveCursor(QTextCursor::End);
    insertHtml(txt);
}

void MvQLogBrowser::parseTask(QString t, QString& desc, QString& cmd, QString& cmdTitle)
{
    desc = t;

    for (QMap<QString, QString>::const_iterator it = keys_.constBegin(); it != keys_.constEnd(); ++it) {
        if (t.contains(it.key())) {
            QStringList lst = t.split(it.key());
            Q_ASSERT(lst.count() >= 2);
            desc = lst[0];
            cmd = lst[1];
            cmdTitle = it.value();
            return;
        }
    }
}

QString MvQLogBrowser::creTitle(QString t)
{
    return "<b><font color=\'" + titleFg.name() + "\'>" + t + ": </font></b>";
}

void MvQLogBrowser::slotTextChanged()
{
    if (hasOutput_ && document()->isEmpty())
        hasOutput_ = false;
}
