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

#include <QComboBox>
#include <QDebug>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QLinearGradient>
#include <QToolButton>

#include "MvQStyleDb.h"
#include "MvQEcLayerDb.h"
#include "MvQRequestPanelHelp.h"
#include "MvMiscellaneous.h"

#include "LineFactory.h"
#include "RequestPanel.h"

//==========================================
//
// MvQEcStyleLine
//
//==========================================

class MvQEcStyleLineWidget : public QWidget
{
public:
    MvQEcStyleLineWidget(MvQEcStyleLine* owner, QWidget* parent) :
        QWidget(parent),
        owner_(owner) {}

protected:
    void mousePressEvent(QMouseEvent*)
    {
        owner_->widgetClicked();
    }

    MvQEcStyleLine* owner_;
};

MvQEcStyleLine::MvQEcStyleLine(RequestPanel& owner, const MvIconParameter& param) :
    MvQRequestPanelLine(owner, param),
    layerParam_("LAYER")
{
    MvQEcStyleLineWidget* w = new MvQEcStyleLineWidget(this, parentWidget_);
    QHBoxLayout* hb         = new QHBoxLayout(w);
    hb->setContentsMargins(0, 0, 0, 0);

    stylePixLabel_  = new QLabel(w);
    styleNameLabel_ = new QLabel(w);
    hb->addWidget(stylePixLabel_);
    hb->addWidget(styleNameLabel_, 1);

    QFont font;
    QFontMetrics fm(font);
    pixSize_ = QSize(180, fm.height() + 4);

    owner_.addWidget(w, row_, 3);

#if 0
    connect(colCb_,SIGNAL(currentIndexChanged(int)),
        this,SLOT(slotCurrentChanged(int)));
#endif
}

void MvQEcStyleLine::widgetClicked()
{
    if (helpTb_) {
        if (!helpTb_->isChecked())
            helpTb_->toggle();
    }
}


void MvQEcStyleLine::next(const MvIconParameter&, const char* /*first*/, const char* /*second*/)
{
}

void MvQEcStyleLine::refresh(const std::vector<std::string>& values)
{
    if (values.size() > 0) {
        if (MvQStyleDbItem* item = MvQStyleDb::instance()->find(values[0])) {
            stylePixLabel_->setPixmap(item->makePixmapToHeight(pixSize_));
            styleNameLabel_->setText(item->name());
            updateHelper();
            return;
        }
    }

    stylePixLabel_->setPixmap(QPixmap());
    styleNameLabel_->clear();
    //changed_ = false;
}


void MvQEcStyleLine::changed(const char* param, const std::string& val)
{
    if (param && strcmp(param, layerParam_.c_str()) == 0) {
        if (MvQEcLayerDbItem* layer = MvQEcLayerDb::instance()->find(val)) {
            std::vector<std::string> vec;
            vec.push_back(layer->defaultStyle().toStdString());
            refresh(vec);
            //Here the style has already been selected and stored in  styleNameLabel_
            owner_.set(param_.name(), styleNameLabel_->text().toStdString());
        }
    }
}

std::string MvQEcStyleLine::layerName() const
{
    Request r                    = owner_.request();
    std::vector<std::string> vec = r.get(layerParam_.c_str());
    return (!vec.empty()) ? vec[0] : std::string();
}

void MvQEcStyleLine::slotHelperEdited(const std::vector<std::string>& values)
{
    if (values.size() > 0 && !values[0].empty()) {
        int idx = metview::fromString<int>(values[0]);
        if (idx >= 0 && idx < MvQStyleDb::instance()->items().count()) {
            MvQStyleDbItem* item = MvQStyleDb::instance()->items()[idx];
            Q_ASSERT(item);
            stylePixLabel_->setPixmap(item->makePixmapToHeight(pixSize_));
            styleNameLabel_->setText(item->name());
            owner_.set(param_.name(), item->name().toStdString());
        }


#if 0
        for(int i=0; i < colCb_->count(); i++)
        {
            if(colCb_->itemData(i).toString().toStdString() == values[0])
            {
                colCb_->setCurrentIndex(i);
                return;
            }
        }

        QString name=QString::fromStdString(values[0]);
        //This sets the current index as well
        setCustomColour(MvQPalette::magics(values[0]),name,name,true);
#endif

        //If the current index did not change the slotCurrentChanged() was
        //not called, so here we need to notify the owner about the change!!
        //if(colCb_->currentIndex() ==  currentPrev)
        //{
        //	owner_.set(param_.name(),name.toStdString());
        //}
    }
}


void MvQEcStyleLine::updateHelper()
{
    if (!helper_)
        return;

    std::vector<std::string> vals;
    vals.push_back(styleNameLabel_->text().toStdString());
    vals.push_back(layerName());

    helper_->refresh(vals);
}

#if 0
void MvQEcStyleLine::slotHelperEditConfirmed()
{
    int index=colCb_->currentIndex();
    if(index != -1)
    {
        QString name=colCb_->itemData(index).toString();
        owner_.set(param_.name(),name.toStdString());
    }
}
#endif

static LineMaker<MvQEcStyleLine> maker1("ecstyle");
