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

 Copyright 2018 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 "MvQEcLayerTreeWidget.h"

#include <QtGlobal>
#include <QAction>
#include <QApplication>
#include <QBuffer>
#include <QClipboard>
#include <QPainter>
#include <QScrollBar>
#include <QSplitter>
#include <QTextEdit>
#include <QTreeView>
#include <QVBoxLayout>

#include "MvQMethods.h"
#include "MvQEcLayerDb.h"
#include "MvQStyleDb.h"
#include "MvQTheme.h"
#include "MvMiscellaneous.h"

//==============================
//
// MvQEcLayerDelegate
//
//==============================

MvQEcLayerDelegate::MvQEcLayerDelegate(QWidget* parent) :
    QStyledItemDelegate(parent),
    borderCol_(MvQTheme::treeItemBorder())
{
    QFont f;
    QFontMetrics fm(f);
    textHeight_ = fm.height();
    pixHeight_  = qMax(textHeight_ + 2, 24);
}

void MvQEcLayerDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
                               const QModelIndex& index) const
{
    painter->save();

    if (index.column() == 0) {
        //Background
        QStyleOptionViewItem vopt(option);
        initStyleOption(&vopt, index);

        const QStyle* style   = vopt.widget ? vopt.widget->style() : QApplication::style();
        const QWidget* widget = vopt.widget;

        //We render everything with the default method
        style->drawControl(QStyle::CE_ItemViewItem, &vopt, painter, widget);

        int row = index.data(Qt::DisplayRole).toInt();
        if (row < 0)
            return;

        QRect rect = option.rect.adjusted(2, 2, -4, -2);
        rect.setWidth(45);

        MvQEcLayerDbItem* item = MvQEcLayerDb::instance()->items()[row];
        Q_ASSERT(item);
        if (item)
            item->paint(painter, rect);

        QString name   = item->name();
        QRect textRect = rect;
        textRect.setX(rect.x() + rect.width());
        textRect.setRight(option.rect.right());
        painter->setPen(MvQTheme::text());
        painter->drawText(textRect, name, Qt::AlignLeft | Qt::AlignVCenter);
    }
    else {
        QStyledItemDelegate::paint(painter, option, index);
    }

    //Render the horizontal border for rows. We only render the top border line.
    //With this technique we miss the bottom border line of the last row!!!
    //QRect fullRect=QRect(0,option.rect.y(),painter->device()->width(),option.rect.height());
    QRect bgRect = option.rect;
    painter->setPen(borderCol_);
    painter->drawLine(bgRect.topLeft(), bgRect.topRight());

    painter->restore();
}

QSize MvQEcLayerDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QSize s = QStyledItemDelegate::sizeHint(option, index);
    return QSize(pixHeight_ * 2 + 10 + s.width(), pixHeight_);
}

//=====================================================
//
// MvQEcLayerTreeWidget
//
//=====================================================

MvQEcLayerTreeWidget::MvQEcLayerTreeWidget(QWidget* parent) :
    QWidget(parent)
{
    //Layout to hold tree and sidebar
    auto* vb = new QVBoxLayout(this);

    vb->setContentsMargins(0, 0, 0, 0);

    splitter_ = new QSplitter(this);
    splitter_->setOpaqueResize(true);
    splitter_->setChildrenCollapsible(false);
    vb->addWidget(splitter_);

    //tree view and model
    tree_ = new QTreeView(this);
    tree_->setRootIsDecorated(false);
    tree_->setUniformRowHeights(true);
    tree_->setMinimumHeight(268);
    splitter_->addWidget(tree_);

    tree_->setItemDelegate(new MvQEcLayerDelegate(this));

    tree_->setSortingEnabled(true);
    tree_->sortByColumn(1, Qt::AscendingOrder);
    //tree_->setModel(sortModel_);

    //Tree context menu
    tree_->setContextMenuPolicy(Qt::ActionsContextMenu);

    auto* acCopyName = new QAction(this);
    acCopyName->setText(tr("&Copy layer name"));
    acCopyName->setShortcut(QKeySequence(tr("Ctrl+C")));
    tree_->addAction(acCopyName);

    connect(acCopyName, SIGNAL(triggered()),
            this, SLOT(slotCopyLayerName()));

    //Tree sidebar
    te_ = new QTextEdit(this);
    splitter_->addWidget(te_);

    te_->setReadOnly(true);

    QFont f;
    f.setPointSize(f.pointSize() - 1);
    te_->setFont(f);
    te_->document()->setDefaultStyleSheet(MvQTheme::htmlTableCss());

    tree_->resizeColumnToContents(0);
}

void MvQEcLayerTreeWidget::setLayer(MvQEcLayerDbItem* item)
{
    te_->clear();

    if (!item)
        return;

    QString txt = "<table width=\'100%\'>";
    txt += MvQ::formatTableRow("Layer", item->name());

    if (!item->title().isEmpty())
        txt += MvQ::formatTableRow("Title", item->title());

    if (MvQStyleDbItem* styleItem = MvQStyleDb::instance()->find(item->defaultStyle().toStdString())) {
        QPixmap pix = styleItem->makePixmapToWidth(QSize(228, 228));
        QByteArray byteArray;
        QBuffer buffer(&byteArray);
        pix.save(&buffer, "PNG");

        txt += MvQ::formatTableRow("Img",
                                   "<img src=\"data:image/png;base64," +
                                       byteArray.toBase64() + "\"/>");
    }

    if (!item->description().isEmpty())
        txt += MvQ::formatTableRow("Description", item->description());

    if (!item->group().isEmpty())
        txt += MvQ::formatTableRow("Group", item->group());

    if (!item->keywords().isEmpty())
        txt += MvQ::formatTableRow("Keywords", item->keywords().join(", "));


    bool hasMarsInfo = !(item->quantiles().isEmpty() && item->steps().isEmpty());

    if (hasMarsInfo) {
        txt += "<tr><td class=\'title\' align=\'center\' colspan=\'2\'><b>Specific values for MARS retrievals</b></td></tr>";
    }

    if (!item->quantiles().isEmpty())
        txt += MvQ::formatTableRow("Quantiles", item->quantiles().join(", "));

    if (!item->steps().isEmpty())
        txt += MvQ::formatTableRow("Steps", item->steps().join(", "));

    txt += "</table>";

    te_->insertHtml(txt);

    //scroll to top
    te_->moveCursor(QTextCursor::Start);
    te_->ensureCursorVisible();
}

void MvQEcLayerTreeWidget::slotCopyLayerName()
{
    QModelIndex idx = tree_->currentIndex();
    if (!idx.isValid())
        return;

    int row = idx.data().toInt();
    if (row >= 0 && row < MvQEcLayerDb::instance()->items().count()) {
        MvQEcLayerDbItem* item = MvQEcLayerDb::instance()->items()[row];
        Q_ASSERT(item);
        MvQ::toClipboard(item->name());
    }
}
