/***************************** 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 <QAction>
#include <QPushButton>
#include <QSettings>
#include <QSortFilterProxyModel>
#include <QSpinBox>
#include <QSplitter>
#include <QStatusBar>
#include <QVBoxLayout>

#include "GeopExaminer.h"
#include "LogHandler.h"
#include "StatusMsgHandler.h"
#include "MvGeoPoints.h"
#include "MvQAbout.h"
#include "MvQArrowSpinWidget.h"
#include "MvQFileInfoLabel.h"
#include "MvGeoPointsModel.h"
#include "MvQLogPanel.h"
#include "MvQTreeView.h"
#include "MvQMethods.h"
#include "MvQPanel.h"
#include "MvQTheme.h"

#ifdef UI_TODO
#include "MvQTreeViewSearchLine.h"
#endif

GeopExaminer::GeopExaminer(QWidget* parent) :
    MvQMainWindow(parent)
{
    // Initializations
    setAttribute(Qt::WA_DeleteOnClose);
    setWindowTitle(tr("Metview - Geopoints Examiner"));

    // Initial size
    setInitialSize(1100, 800);

    setupDataBox();
    setupFindBox();

    // Main splitter
    mainSplitter_ = new QSplitter;
    mainSplitter_->setOrientation(Qt::Vertical);
    mainSplitter_->setOpaqueResize(false);
    setCentralWidget(mainSplitter_);

    // The main layout (the upper part of mainSplitter)
    auto* mainLayout = new QVBoxLayout;
    mainLayout->setObjectName(QString::fromUtf8("vboxLayout"));
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(1);

    auto* w = new QWidget(this);
    w->setLayout(mainLayout);
    mainSplitter_->addWidget(w);

    // File info area
    fileInfoLabel_ = new MvQFileInfoLabel(this);
    mainLayout->addWidget(fileInfoLabel_);

    metadataLabel_ = new QLabel(this);
    metadataLabel_->setProperty("type", "info");
    mainLayout->addWidget(metadataLabel_);
    metadataLabel_->hide();

    // Central area
    mainLayout->addWidget(dataPanel_, 1);

    // Log
    logPanel_ = new MvQLogPanel(this);
    mainSplitter_->addWidget(logPanel_);

    //--------------------------
    // Status bar
    //--------------------------

    statusMessageLabel_ = new QLabel("", this);
    statusMessageLabel_->setFrameShape(QFrame::NoFrame);
    statusBar()->addPermanentWidget(statusMessageLabel_, 1);  // '1' means 'please stretch me when resized'

    StatusMsgHandler::instance()->init(statusMessageLabel_);

    //----------------------------
    // Setup menus and toolbars
    //----------------------------

    // Initialize user interface actions
    setupEditActions();
    setupViewActions();
    setupHelpActions();

    setupMenus(menuItems_);

    readSettings();
}

GeopExaminer::~GeopExaminer()
{
    writeSettings();
    if (data_) {
        delete data_;
    }
}

void GeopExaminer::setupEditActions()
{
#if 0
    QAction *actionFind_=MvQMainWindow::createAction(MvQMainWindow::FindAction,this);
	connect(actionFind_,SIGNAL(triggered(bool)),
		findPanel_,SLOT(setHidden(bool)));
				
	QAction *actionFindNext=MvQMainWindow::createAction(MvQMainWindow::FindNextAction,this);
	connect(actionFindNext,SIGNAL(triggered(bool)),
		findPanel_,SLOT(slotFindNext(bool)));	
		
	QAction *actionFindPrev=MvQMainWindow::createAction(MvQMainWindow::FindPreviousAction,this);
	connect(actionFindPrev,SIGNAL(triggered(bool)),
		findPanel_,SLOT(slotFindPrev(bool)));
		
	MvQMainWindow::MenuType menuType=MvQMainWindow::EditMenu;
	
	menuItems_[menuType].push_back(new MvQMenuItem(actionFind_,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionFindNext,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionFindPrev,MvQMenuItem::MenuTarget));
#endif
}

void GeopExaminer::setupViewActions()
{
    actionFileInfo_ = new QAction(this);
    actionFileInfo_->setObjectName(QString::fromUtf8("actionFileInfo"));
    actionFileInfo_->setText(tr("File info"));
    actionFileInfo_->setCheckable(true);
    actionFileInfo_->setChecked(true);
    actionFileInfo_->setToolTip(tr("View file info"));
    QIcon icon;
    icon.addPixmap(QPixmap(QString::fromUtf8(":/examiner/info_light.svg")), QIcon::Normal, QIcon::Off);
    actionFileInfo_->setIcon(icon);

    actionLog_ = new QAction(this);
    actionLog_->setObjectName(QString::fromUtf8("actionLog"));
    actionLog_->setText(tr("&Log"));
    actionLog_->setCheckable(true);
    actionLog_->setChecked(false);
    actionLog_->setToolTip(tr("View log"));
    QIcon icon1;
    icon1.addPixmap(QPixmap(QString::fromUtf8(":/examiner/log.svg")), QIcon::Normal, QIcon::Off);
    actionLog_->setIcon(icon1);

    logPanel_->hide();  // hide log area

    // Signals and slots
    connect(actionFileInfo_, SIGNAL(toggled(bool)),
            fileInfoLabel_, SLOT(setVisible(bool)));

    connect(actionLog_, SIGNAL(toggled(bool)),
            logPanel_, SLOT(setVisible(bool)));

    MvQMainWindow::MenuType menuType = MvQMainWindow::ViewMenu;
    menuItems_[menuType].push_back(new MvQMenuItem(actionFileInfo_));
    menuItems_[menuType].push_back(new MvQMenuItem(actionLog_));
}

void GeopExaminer::setupHelpActions()
{
    // About
    auto* actionAbout = new QAction(this);
    actionAbout->setObjectName(QString::fromUtf8("actionAbout"));
    actionAbout->setText(tr("&About Geopoints Examiner"));

    connect(actionAbout, SIGNAL(triggered()), this, SLOT(slotShowAboutBox()));

    MvQMainWindow::MenuType menuType = MvQMainWindow::HelpMenu;
    menuItems_[menuType].push_back(new MvQMenuItem(actionAbout, MvQMenuItem::MenuTarget));
}

void GeopExaminer::setupDataBox()
{
    // Build a box layout
    auto* dataLayout = new QVBoxLayout;
    dataLayout->setContentsMargins(0, 0, 0, 0);
    dataPanel_ = new QWidget(this);
    dataPanel_->setLayout(dataLayout);

    // Combo box for index selection
    auto* gotoW = new MvQPanel(this);
    dataLayout->addWidget(gotoW);

    auto* gotoLayout = new QHBoxLayout(gotoW);
    gotoLayout->setContentsMargins(4, 0, 0, 4);

    auto* messageTitleLab = new QLabel(tr("&Row:"), this);
    messageTitleLab->setProperty("panelStyle", "2");
    dataRowSpin_ = new MvQArrowSpinWidget(this);
    messageTitleLab->setBuddy(dataRowSpin_->spin());

    gotoLayout->addWidget(messageTitleLab);
    gotoLayout->addWidget(dataRowSpin_);
    gotoLayout->addStretch(1);

    connect(dataRowSpin_, SIGNAL(valueChanged(int)),
            this, SLOT(slotDataRowSpinChanged(int)));

    // Instantiate the model
    gpModel_ = new MvQGeoPointsDataModel(this);

    // Instantiate the sort model
    gpSortModel_ = new QSortFilterProxyModel(this);
    gpSortModel_->setSourceModel(gpModel_);
    gpSortModel_->setDynamicSortFilter(true);
    gpSortModel_->setSortRole(Qt::UserRole);

    // Build a tree to show the meta data
    treeData_ = new MvQTreeView(this);
    treeData_->setObjectName("geopTreeData");
    treeData_->setAlternatingRowColors(true);
    treeData_->setAllColumnsShowFocus(true);
    treeData_->setUniformRowHeights(true);
    treeData_->setRootIsDecorated(false);
    treeData_->setActvatedByKeyNavigation(true);

    // Set the sort model
    treeData_->setModel(gpSortModel_);
    treeData_->setSortingEnabled(true);

    connect(treeData_, SIGNAL(clicked(QModelIndex)),
            this, SLOT(slotSelectDataRow(QModelIndex)));

    connect(treeData_, SIGNAL(activated(const QModelIndex&)),
            this, SLOT(slotSelectDataRow(const QModelIndex&)));

    dataLayout->addWidget(treeData_, 1);
}

void GeopExaminer::setupFindBox()
{
#ifdef UI_TODO
    dataFind_ = new MvQTreeViewSearchLine(treeData_, 1, "");

    findPanel_ = new MvQSearchLinePanel;
    findPanel_->addSearchLine(dataFind_, treeData_);
    findPanel_->hide();
#endif
}

bool GeopExaminer::initMetaData(const std::string& filename)
{
    // Clean metadata if already exists
    if (data_) {
        delete data_;
        data_ = nullptr;
    }

    // Write initial message in the log area
    GuiLog().task() << "Loading geopoints file";

    data_ = new MvGeoPoints();
    bool ok = data_->load(filename.c_str());

    updateFileInfoLabel();
    updateMetadataLabel();

    // Check if it is a valid geopoints file
    if (!ok) {
        delete data_;
        data_ = nullptr;
        GuiLog().error() << "Could not open geopoints file";
        StatusMsgHandler::instance()->failed();
        return false;
    }

    StatusMsgHandler::instance()->done();

    // Instantiate the model
    /*gpModel_ = new MvQGeoPointsDataModel;

    // Instantiate the sort model
    gpSortModel_= new QSortFilterProxyModel;
    gpSortModel_->setSourceModel(gpModel_);
    gpSortModel_->setDynamicSortFilter(true);

    // Set the sort model
    treeData_->setModel(gpSortModel_);
    treeData_->setSortingEnabled(true);*/

    // Load data
    gpModel_->dataIsAboutToChange();
    gpModel_->setBaseData(data_);

    // Sort the first column
    treeData_->sortByColumn(0, Qt::AscendingOrder);

    // Set min/max values
    // dataRowSpin_->setRange(1,data_->count());
    dataRowSpin_->reset(data_->count(), false);

#if 0  // rezise according to the column contents
	for(int i=0;i < gpModel_->columnCount()-1; i++)
	{ 
		treeData_->resizeColumnToContents(i);
	}
#endif

    return true;
}

void GeopExaminer::updateFileInfoLabel()
{
    fileInfoLabel_->setGeopTextLabel(QString::fromStdString(data_->path()), QString::fromStdString(data_->sFormat()), data_->count());
}

void GeopExaminer::updateMetadataLabel()
{
    QString t;
    if (data_) {
        auto subCol = MvQTheme::subText();
        auto bold = MvQTheme::boldFileInfoTitle();
        auto m = data_->metadataConst();
        for (const auto& v : m) {
            auto key = QString::fromStdString(v.first);
            auto val = QString::fromStdString(v.second.toString());
            t += MvQ::formatText(key + ": ", subCol, bold) + val + " ";
        }
    }
    if (!t.isEmpty()) {
        metadataLabel_->setText(t);
        metadataLabel_->show();
    }
    else {
        metadataLabel_->hide();
    }
}

void GeopExaminer::slotShowAboutBox()
{
    MvQAbout about("Geopoints Examiner", "", MvQAbout::MetviewVersion);
    about.exec();
}

void GeopExaminer::slotDataRowSpinChanged(int msgNumber)
{
    if (ignoreDataRowSpinChangeSignal_)
        return;

    QModelIndex srcIndex = gpModel_->index(msgNumber - 1, 0);
    treeData_->setCurrentIndex(gpSortModel_->mapFromSource(srcIndex));
}

void GeopExaminer::slotSelectDataRow(const QModelIndex& index)
{
    QModelIndex srcIndex = gpSortModel_->mapToSource(index);

    int cnt = gpModel_->data(gpModel_->index(srcIndex.row(), 0)).toInt();
    if (cnt > 0) {
        ignoreDataRowSpinChangeSignal_ = true;
        dataRowSpin_->setValue(cnt, false);
        ignoreDataRowSpinChangeSignal_ = false;
    }
}

void GeopExaminer::writeSettings()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-GeopExaminer");

    settings.beginGroup("mainWindow");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("mainSplitter", mainSplitter_->saveState());
    settings.setValue("actionFileInfoStatus", actionFileInfo_->isChecked());
    settings.endGroup();
}

void GeopExaminer::readSettings()
{
    QSettings settings(MVQ_QSETTINGS_DEFAULT_ARGS, "MV4-GeopExaminer");

    settings.beginGroup("mainWindow");
    restoreGeometry(settings.value("geometry").toByteArray());
    mainSplitter_->restoreState(settings.value("mainSplitter").toByteArray());

    if (settings.value("actionFileInfoStatus").isNull())
        actionFileInfo_->setChecked(true);
    else
        actionFileInfo_->setChecked(settings.value("actionFileInfoStatus").toBool());

    settings.endGroup();
}
