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

 Copyright 2017 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 "LocationWidget.h"

#include "BufrLocationCollector.h"
#include "MvKeyProfile.h"
#include "MvQKeyProfileModel.h"

LocationWidget::LocationWidget(QWidget* parent) :
    QWidget(parent),
    mode_(LocationMode),
    maxNum_(500000),
    inChangeFromMap_(false),
    inChangeFromTree_(false),
    inUpdateMessage_(false)
{
    setupUi(this);

    bW_->hide();
    maxLabel_->setProperty("headerStyle", "1");
    maxSpin_->setMaximum(1000000);
    maxSpin_->setMinimum(1);
    maxSpin_->setValue(100000);

    controlW_->setProperty("panelStyle", "2");
    numLabel_->setProperty("panelStyle", "2");
    numLabel_->setText("");

    model_ = new MvQKeyProfileModel(this);
    //model_->setShadeFirstColumn(true);

    sortModel_ = new MvQKeyProfileSortFilterModel(this);
    sortModel_->setSourceModel(model_);
    sortModel_->setDynamicSortFilter(true);
    sortModel_->setFilterRole(Qt::UserRole);
    sortModel_->setFilterFixedString("1");
    sortModel_->setFilterKeyColumn(0);

    tree_->setSortingEnabled(true);
    tree_->setModels(model_, sortModel_);
    tree_->setUniformRowHeights(true);
    tree_->setProperty("mvStyle", 1);

    prof_ = new MvKeyProfile("location");

    MvKey* key = new MvKey("msg", "Message");
    key->setRole(MvKey::MessageIndexRole);
    key->setValueType(MvKey::IntType);
    prof_->addKey(key);

    key = new MvKey("subset", "Subset");
    key->setRole(MvKey::SubsetIndexRole);
    key->setValueType(MvKey::IntType);
    prof_->addKey(key);

    key = new MvKey("rank", "Rank");
    key->setRole(MvKey::RankRole);
    key->setValueType(MvKey::IntType);
    prof_->addKey(key);

    key = new MvKey("lat", "Latitude");
    key->setRole(MvKey::LatitudeRole);
    key->setValueType(MvKey::DoubleType);
    key->setValuePrecision(4);
    prof_->addKey(key);

    key = new MvKey("lon", "Longitude");
    key->setRole(MvKey::LongitudeRole);
    key->setValueType(MvKey::DoubleType);
    key->setValuePrecision(4);
    prof_->addKey(key);

    connect(map_->view(), SIGNAL(currentChanged(int)),
            this, SLOT(slotCurrentChangedInMap(int)));

    connect(tree_, SIGNAL(selectionChanged(QModelIndex)),
            this, SLOT(slotCurrentChangedInTree(QModelIndex)));
}

void LocationWidget::clear()
{
    model_->clear();
    map_->view()->clearPoints();
    updateNumLabel(-1, -1);
}

BufrLocationCollector* LocationWidget::makeCollector()
{
    return new BufrLocationCollector(prof_->clone(), maxNum_);
}

void LocationWidget::updateNumLabel(int num, int totalNum)
{
    QString s;

    if (mode_ == LocationMode) {
        if (num < 0) {
            s = "Locations are not yet scanned!";
        }
        else if (totalNum <= maxNum_) {
            s = "Number of locations: <b>" + QString::number(num) + "</b>";
        }
        else {
            QColor col(252, 166, 141);
            s = "Number of locations: <b>" + QString::number(num) +
                " </b><font color=\'" + col.name() +
                "\'> (out of " + QString::number(totalNum) +
                ", maximum number reached!)</font>";
        }
    }
    else {
        //in this case num=totalNum
        if (num < 0) {
            s = "No extracted data is available!";
        }
        else {
            s = "Number of extracted rows: <b>" + QString::number(num) + "</b>";

            if (num > maxNum_) {
                QColor col(252, 166, 141);
                s = "Number of locations shown: <b>" + QString::number(maxNum_) +
                    " </b><font color=\'" + col.name() +
                    "\'> (out of " + QString::number(num) +
                    ", maximum number reached!)</font>";
            }
        }
    }

    numLabel_->setText(s);
}

void LocationWidget::update(BufrLocationCollector* collector)
{
    mode_ = LocationMode;

    Q_ASSERT(collector);
    MvKeyProfile* prof = collector->profile();
    Q_ASSERT(prof);
    model_->setKeyProfile(prof);

    MvKey* lat = prof->key(MvKey::LatitudeRole);
    MvKey* lon = prof->key(MvKey::LongitudeRole);
    Q_ASSERT(lat);
    Q_ASSERT(lon);
    Q_ASSERT(collector->maxNum() == maxNum_);

    updateNumLabel(prof->valueNum(), collector->totalNum());

    map_->view()->addPoints(lat->doubleValue(), lon->doubleValue());

    delete collector;
}

void LocationWidget::update(MvKeyProfile* prof)
{
    mode_ = DataMode;

    Q_ASSERT(prof);
    model_->setKeyProfile(prof);  //the model takes ownership of the profile

    MvKey* lat = prof->key(MvKey::LatitudeRole);
    MvKey* lon = prof->key(MvKey::LongitudeRole);

    if (lat && lon) {
        map_->view()->addPoints(lat->doubleValue(), lon->doubleValue());
    }

    //Q_ASSERT(lat);
    //Q_ASSERT(lon);
    //Q_ASSERT(collector->maxNum() == maxNum_);

    int num = prof->valueNum();
    updateNumLabel(num, num);

    //map_->view()->addPoints(lat->doubleValue(),lon->doubleValue());}
}

void LocationWidget::updateMessage(int msg)
{
    //TODO
    //return;

    if (MvKeyProfile* prof = model_->keyProfile()) {
        MvKey* mk = prof->key(MvKey::MessageIndexRole);
        Q_ASSERT(mk);
        std::size_t num = mk->intValue().size();
        for (std::size_t i = 0; i < num; i++) {
            if (mk->intValue()[i] == msg) {
                inUpdateMessage_ = true;
                tree_->setCurrentIndex(sortModel_->mapFromSource(model_->index(i, 0)));
                tree_->scrollTo(tree_->currentIndex());
                inUpdateMessage_ = false;
                return;
            }
        }
    }
}

void LocationWidget::slotCurrentChangedInMap(int index)
{
    if (inChangeFromTree_ || inUpdateMessage_)
        return;

    MvKeyProfile* prof = model_->keyProfile();
    Q_ASSERT(prof);

    MvKey* msg = prof->key(MvKey::MessageIndexRole);
    Q_ASSERT(msg);

    int msgIndex     = msg->intValue()[index];
    inChangeFromMap_ = true;
    tree_->setCurrentIndex(sortModel_->mapFromSource(model_->index(index, 0)));
    tree_->scrollTo(tree_->currentIndex());
    Q_EMIT messageSelected(msgIndex);
    inChangeFromMap_ = false;
}

void LocationWidget::slotCurrentChangedInTree(const QModelIndex& sortIndex)
{
    if (inChangeFromMap_)
        return;

    QModelIndex index = sortModel_->mapToSource(sortIndex);
    if (index.isValid()) {
        MvKeyProfile* prof = model_->keyProfile();
        Q_ASSERT(prof);
        MvKey* msg = prof->key(MvKey::MessageIndexRole);
        Q_ASSERT(msg);

        int msgIndex      = msg->intValue()[index.row()];
        inChangeFromTree_ = true;
        map_->view()->setCurrentPoint(index.row());

        if (!inUpdateMessage_) {
            Q_EMIT messageSelected(msgIndex);
        }
        inChangeFromTree_ = false;
    }
}
