/***************************** 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 "MvQStyleTreeWidget.h"

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

#include "MvQMethods.h"
#include "MvQStyleDb.h"
#include "MvMiscelaneous.h"

//==============================
//
// MvQStyleDelegate
//
//==============================

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

void MvQStyleDelegate::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);

        MvQStyleDbItem* item = MvQStyleDb::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(QColor(50, 51, 52));
        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 MvQStyleDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QSize s = QStyledItemDelegate::sizeHint(option, index);
    return QSize(s.width(), pixHeight_);
}

//=====================================================
//
// MvQStyleTreeWidget
//
//=====================================================

MvQStyleTreeWidget::MvQStyleTreeWidget(QWidget* parent) :
    QWidget(parent)
{
    //Layout to hold tree and sidebar
    QVBoxLayout* 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 MvQStyleDelegate(this));

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

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

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

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

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

    te_->setReadOnly(true);

    QFont f;
    f.setPointSize(f.pointSize() - 1);
    te_->setFont(f);

    //Set css for the text formatting
    QString cssDoc =
        "td {padding-left: 3px; paddig-top: 1px; padding-bottom: 1px; background-color: #F3F3F3;color: #000000;} \
                    td.title {padding-left: 2px; padding-top: 1px; padding-bottom: 1px;background-color: #e3e6f3; color: #000000;}";


    te_->document()->setDefaultStyleSheet(cssDoc);
}

void MvQStyleTreeWidget::setStyle(MvQStyleDbItem* item)
{
    te_->clear();

    if (!item)
        return;
    ;

    QColor bg(243, 243, 243);
    QColor fg(50, 51, 52);

    QPixmap pix = item->makePixmapToWidth(QSize(228, 228));
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    pix.save(&buffer, "PNG");

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

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

    if (!item->description().isEmpty())
        txt += MvQ::formatTableRow("Method", item->description(), bg, fg, true);

    if (!item->layers().isEmpty())
        txt += MvQ::formatTableRow("Layers", item->layers().join(", "), bg, fg, true);

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

    if (!item->colours().isEmpty())
        txt += MvQ::formatTableRow("Colours", item->colours().join(", "), bg, fg, true);

    txt += "</table>";

    te_->insertHtml(txt);
}

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

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

void MvQStyleTreeWidget::toClipboard(QString txt) const
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
    QClipboard* cb = QGuiApplication::clipboard();
    cb->setText(txt, QClipboard::Clipboard);
    cb->setText(txt, QClipboard::Selection);
#else
    QClipboard* cb = QApplication::clipboard();
    cb->setText(txt, QClipboard::Clipboard);
    cb->setText(txt, QClipboard::Selection);
#endif
}
