/***************************** 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"

static QColor okBg(230, 231, 232);
static QColor errBg(223, 224, 222);
static QColor titleBg(50, 50, 50);

QMap<QString, QString> MvQLogBrowser::keys_;

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

    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()
{
}

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=\'#C21C1C\'> <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=\'" + titleBg.name() + "\'>" + t + ": </font></b>";
}

#if 0
QString MvQLogBrowser::creIconCell(int iconSize,QString iconPath)
{
    return "<td width=\'" + QString::number(iconSize+8) + "\'><img src=\'" + iconPath +
            "\' width=\'" +   QString::number(iconSize) + "\'" +
            "\' height=\'" +   QString::number(iconSize) + "\'></td>";
}

QString MvQLogBrowser::creError()
{
    QString t=toHtml();
    qDebug() << t;
    int i=t.lastIndexOf("<table");
    if(i != -1)
    {
         QString t1=t.left(i);
         QString t2=t.mid(i,-1);

         qDebug() << "t1" << t1;
         qDebug() << "t2" << t2;

         t2.replace("log_info.svg","log_error.svg");

         qDebug() << "t2" << t2;

         return t1 + t2;
    }
    return QString();
}

#endif

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