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

 Copyright 2019 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 "FunctionWebWidget.h"

#include <QDebug>
#include <QLabel>
#include <QTreeWidgetItem>
#include <QUrl>
#include <QVBoxLayout>

#ifdef METVIEW_QT_WEBENGINE
#include <QWebEngineView>
#endif

#include "LanguageHelper.h"
#include "IconClassHelp.h"
#include "VerbFunctionHelp.h"
#include "MessageLabel.h"
#include "MvQMethods.h"

#include "ui_FunctionWebWidget.h"

FunctionWebWidget::FunctionWebWidget(QWidget* parent) :
    QWidget(parent),
    ui_(new Ui::FunctionWebWidget),
    language_(nullptr),
#ifdef METVIEW_QT_WEBENGINE
    webView_(nullptr),
#endif
    fn_(nullptr),
    ignoreWebGroupSelection_(false)

{
    ui_->setupUi(this);

    connect(ui_->showFunctionListTb,SIGNAL(clicked()),
            this, SIGNAL(functionListRequested()));

    ui_->functionNameLabel->setStyleSheet("QLabel{color: rgb(40,40,40);}");

    ui_->descriptionLabel->setWordWrap(true);
    ui_->descriptionLabel->setStyleSheet("QLabel{color: rgb(0,0,0); background: rgb(247,247,247); \
                                         padding: 5px; border: 1px solid rgb(140,140,140);}");


    connect(ui_->descriptionTree,SIGNAL(itemClicked(QTreeWidgetItem*,int)),
            this,SLOT(selectWebGroup(QTreeWidgetItem*,int)));

    hideDescription();

    // set tree view height
    QFont f;
    QFontMetrics fm(f);
    ui_->descriptionTree->setFixedHeight(5*fm.height()+10);

    QVBoxLayout* vb = new QVBoxLayout(ui_->webViewHolder);
    vb->setContentsMargins(0,0,0,0);
    vb->setSpacing(0);

#ifdef METVIEW_QT_WEBENGINE
    if (MvQ::hasOpenGLSupport())  {
        webView_ = new QWebEngineView(this);
        vb->addWidget(webView_);
    } else {
        MessageLabel* label = new MessageLabel(this);
       /*label->setWordWrap(true);
        label->setStyleSheet("QLabel{background: rgb(255,180,180); \
                             margin: 2px; border: 1px solid rgb(255,70,70);}");*/
        label->showWarning(tr("<b>Cannot load</b> web-based documentation viewer! \
This would require <b>OpenGL support</b>, but it does not seem to be \
available in the current graphical environment."));
        vb->addWidget(label);
        vb->addStretch(1);
    }
#else
    //MessageLabel* label = new MessageLabel(this);
    //label->showWarning(tr("The <b>web documentation view</b> is only avialable when Metview is built with <b>QtWebEngineWidgets</b>."));
    //vb->addWidget(label);
    //vb->addStretch(1);
#endif
}

void FunctionWebWidget::clear()
{
    ui_->functionNameLabel->setText("");
    hideDescription();
    fn_ = 0;
    webGroup_.clear();
}

void FunctionWebWidget::hideDescription()
{
    ui_->descriptionLabel->hide();
    ui_->descriptionTree->hide();
}

void FunctionWebWidget::setLanguage(LanguageHelper *language)
{
    clear();
    language_ = language;
}

void FunctionWebWidget::showFunction(QString functionName)
{
    if(!hasData())
        return;

    showFunction(language_->functionHelp()->function(functionName));
}

void FunctionWebWidget::showFunction(VerbFunctionHelpFunction* fn)
{
    if (!hasData())
        return;

    hideDescription();

    if (!fn) {
        clear();
        return;
    }

    fn_ =fn;
    ui_->functionNameLabel->setText(" Function: <b>" + fn->name() + "()</b>");

    //single description
    if (fn->descriptions().count() <= 1) {
        ui_->descriptionLabel->show();
        QString v;
        if (fn->descriptions().count() == 1) {
            webGroup_ = fn->descriptions().keys()[0];
            v = fn->descriptions().values()[0].simplified();
            if (!v.isEmpty())
                ui_->descriptionLabel->setText(v);
        }
    //multiple descriptions
    } else {
        ui_->descriptionTree->show();
        setDescriptions(fn);
    }

    loadWebDoc();
}

void FunctionWebWidget::loadWebDoc()
{
#ifdef METVIEW_QT_WEBENGINE
    if (hasView() && fn_ && !webGroup_.isEmpty()) {
        QString web = language_->functionHelp()->url(webGroup_,fn_->name());
        qDebug() << "FunctionWebWidget::loadWebDoc() -->" << web;
        webView_->load(QUrl(web));
    }
#endif
}

bool FunctionWebWidget::hasData() const
{
    return (language_ && language_->hasVerbFunctionHelp() &&
             !language_->functionHelp()->isEmpty());
}

bool FunctionWebWidget::hasView() const
{
#ifdef METVIEW_QT_WEBENGINE
    return webView_ != nullptr;
#else
    return false;
#endif
}

void FunctionWebWidget::setDescriptions(VerbFunctionHelpFunction *fn)
{
    Q_ASSERT(fn);
    Q_ASSERT(fn->descriptions().count() > 1);

    ui_->descriptionTree->clear();
    ui_->descriptionTree->setColumnCount(2);
    QStringList headers;
    headers << tr("Type") << tr("Description");
    ui_->descriptionTree->setHeaderLabels(headers);

    QList<QTreeWidgetItem*> items;

    webGroup_.clear();
    foreach(QString group, fn->descriptions().keys()) {
        QStringList rowData;

        // we select the first group by default
        if (webGroup_.isEmpty()) {
            webGroup_ = group;
        }

        rowData << group << fn->descriptions().value(group);
        items.append(new QTreeWidgetItem((QTreeWidget*)0, rowData));
    }

    ui_->descriptionTree->insertTopLevelItems(0, items);

    if(!items.empty())
    {
        ignoreWebGroupSelection_=true;
        ui_->descriptionTree->setCurrentItem(items[0]);
        ignoreWebGroupSelection_=false;
    }
}

void FunctionWebWidget::selectWebGroup(QTreeWidgetItem* item,int)
{
    if (!ignoreWebGroupSelection_ && item) {
        webGroup_ = item->text(0);
        loadWebDoc();
    }
}

void FunctionWebWidget::readSettings(QSettings&)
{

}

void FunctionWebWidget::writeSettings(QSettings&)
{

}
