/***************************** 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 <QButtonGroup>
#include <QDebug>
#include <QLabel>
#include <QListWidget>
#include <QHBoxLayout>
#include <QPainter>
#include <QStackedLayout>
#include <QToolButton>
#include <QVBoxLayout>

#include "MgQSceneItem.h"

#include "MvQDataWidget.h"
#include "MvQLayerDataWidget.h"
#include "MvQLayerMetaDataWidget.h"
#include "MvQTheme.h"

MvQDataWidget::MvQDataWidget(MgQPlotScene* scene, MvQPlotView* plotView, QWidget* parent) :
    QWidget(parent),
    sceneItem_(nullptr),
    layer_(nullptr),
    metaLoaded_(false),
    dataLoaded_(false)
{
    auto* layout = new QVBoxLayout;
    layout->setContentsMargins(2, 2, 2, 2);
    setLayout(layout);

    auto* hb = new QHBoxLayout;
    hb->setContentsMargins(0, 0, 0, 0);
    previewLabel_ = new QLabel(this);
    titleLabel_ = new QLabel(this);
    titleLabel_->setWordWrap(true);
    titleLabel_->setProperty("type", "title");

    hb->addWidget(previewLabel_);
    hb->addWidget(titleLabel_, 1);

    auto* backTb = new QToolButton(this);
    backTb->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    backTb->setText(tr("Layer list"));
    backTb->setIcon(QPixmap(QString::fromUtf8(":/uPlot/narrow_arrow_left.svg")));
    hb->addWidget(backTb);

    connect(backTb, SIGNAL(clicked()),
            this, SIGNAL(layerListRequested()));

    layout->addLayout(hb);

    // Top row
    hb = new QHBoxLayout;
    hb->setContentsMargins(0, 0, 0, 0);
    layout->addLayout(hb);

    showMetaTb_ = new QToolButton(this);
    showMetaTb_->setText(tr("Metadata"));
    showMetaTb_->setToolTip(tr("View metadata"));
    showMetaTb_->setCheckable(true);
    showMetaTb_->setChecked(false);
    hb->addWidget(showMetaTb_);

    showDataTb_ = new QToolButton(this);
    showDataTb_->setText(tr("Values"));
    showDataTb_->setToolTip(tr("View values"));
    showDataTb_->setCheckable(true);
    showDataTb_->setChecked(false);
    hb->addWidget(showDataTb_);
    hb->addStretch(1);

    showBg_ = new QButtonGroup(this);
    showBg_->setExclusive(true);
    showBg_->addButton(showMetaTb_, 0);
    showBg_->addButton(showDataTb_, 1);

    connect(showBg_, SIGNAL(buttonClicked(QAbstractButton*)),
            this, SLOT(slotShowContentsByButton(QAbstractButton*)));

    //----------------------
    // Central
    //----------------------

    centralLayout_ = new QStackedLayout;
    layout->addLayout(centralLayout_, 1);

    //----------------------
    // Metadata widget
    //----------------------

    metaWidget_ = new MvQLayerMetaDataWidget();
    centralLayout_->addWidget(metaWidget_);
    Q_ASSERT(centralLayout_->count() - 1 == MetadataContentsIndex);

    //----------------------
    // Data widget
    //----------------------

    dataWidget_ = new MvQLayerDataWidget(scene, plotView);
    centralLayout_->addWidget(dataWidget_);
    Q_ASSERT(centralLayout_->count() - 1 == DataContentsIndex);
}

MvQDataWidget::~MvQDataWidget() = default;

void MvQDataWidget::setLayer(MgQLayerItem* layer)
{
    Q_ASSERT(layer);
    layer_ = layer;
    updateTitle();
    int currentId = centralLayout_->currentIndex();
    metaLoaded_ = false;
    dataLoaded_ = false;
    showContents(currentId);
}

void MvQDataWidget::clear()
{
    layer_ = nullptr;
    metaLoaded_ = false;
    dataLoaded_ = false;
    updateTitle();
}

void MvQDataWidget::slotShowContentsByButton(QAbstractButton* b)
{
    showContents(showBg_->id(b));
}

void MvQDataWidget::showContents(int id)
{
    if (id == MetadataContentsIndex) {
        if (!metaLoaded_) {
            metaWidget_->reset(sceneItem_, layer_);
            metaLoaded_ = true;
        }
        else {
            metaWidget_->setLayer(layer_);
        }
    }
    else if (id == DataContentsIndex) {
        if (!dataLoaded_) {
            dataWidget_->reset(sceneItem_, layer_);
            dataLoaded_ = true;
        }
        else {
            dataWidget_->setLayer(layer_);
        }
    }

    centralLayout_->setCurrentIndex(id);
}

void MvQDataWidget::slotFrameChanged()
{
    switch (centralLayout_->currentIndex()) {
        case MetadataContentsIndex:
            metaWidget_->slotFrameChanged();
            break;
        case DataContentsIndex:
            dataWidget_->slotFrameChanged();
            break;
        default:
            break;
    }
}

void MvQDataWidget::slotPlotScaleChanged()
{
    dataWidget_->updateProbe();
}


void MvQDataWidget::layersAreAboutToChange()
{
    lastSelectedLayerText_.clear();
    if (layer_) {
        lastSelectedLayerText_ = layerTitle(layer_);
        clear();
    }
}

void MvQDataWidget::reset(MgQSceneItem* sceneItem)
{
    clear();

    sceneItem_ = sceneItem;
    MgQLayerItem* lastLayer = nullptr;
    MgQLayerItem* layer = nullptr;

    if (sceneItem_ != nullptr) {
        for (int i = sceneItem_->layerItems().count() - 1; i >= 0; i--) {
            MgQLayerItem* item = sceneItem_->layerItems().at(i);
            lastLayer = item;
            if (lastSelectedLayerText_ == layerTitle(item)) {
                layer = item;
                break;
            }
        }
    }
    if (!layer)
        layer = lastLayer;

    if (layer) {
        setLayer(layer);
    }
}

void MvQDataWidget::updateTitle()
{
    if (layer_) {
        QPixmap pix = QPixmap::fromImage(layer_->preview().scaled(QSize(48, 48), Qt::KeepAspectRatio));
        QPainter painter(&pix);
        painter.setPen(MvQTheme::pen("uplot", "preview_border"));
        painter.drawRect(pix.rect().adjusted(1, 1, -1, -1));
        previewLabel_->setPixmap(pix);

        QString titleTxt = layerTitle(layer_);
        // We modify the text by inserting zero-width white space after each char. This allows
        // text wrapping even when the title is a single word. See: METV-3172
        if (titleTxt.size() > 30) {
            titleTxt = titleTxt.split("").join(QChar(0x200b)).simplified();
        }
        titleLabel_->setText(titleTxt);
    }
    else {
        previewLabel_->clear();
        titleLabel_->clear();
    }
}

QString MvQDataWidget::layerTitle(MgQLayerItem* layer) const
{
    if (layer) {
        QString str(layer->layer().name().c_str());
        QStringList lst = str.split("/");
        if (!lst.isEmpty())
            return lst.last();
    }
    return {};
}


void MvQDataWidget::writeSettings(QSettings& settings)
{
    settings.beginGroup("MvQDataWidget");

    settings.setValue("id", centralLayout_->currentIndex());
    settings.setValue("histoEnabled", metaWidget_->isHistoEnabled());
    settings.setValue("histoVisdefIndex", metaWidget_->histoVisdefCurrentIndex());
    settings.setValue("statsEnabled", metaWidget_->isStatsEnabled());

    settings.endGroup();

    dataWidget_->writeSettings(settings);
}

void MvQDataWidget::readSettings(QSettings& settings)
{
    settings.beginGroup("MvQDataWidget");

    QVariant val;

    val = settings.value("id");
    QAbstractButton* tb = showBg_->button((val.isNull()) ? 0 : val.toInt());
    if (tb)
        tb->click();
    else
        showBg_->button(0)->click();

    val = settings.value("histoEnabled");
    metaWidget_->setHistoEnabled((val.isNull()) ? true : val.toBool());

    val = settings.value("histoVisdefIndex");
    metaWidget_->setHistoVisdefInitialIndex((val.isNull()) ? 0 : val.toInt());

    val = settings.value("statsEnabled");
    metaWidget_->setStatsEnabled((val.isNull()) ? true : val.toBool());

    settings.endGroup();

    dataWidget_->readSettings(settings);
}
