/***************************** 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"

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

GeopExaminer::GeopExaminer(QWidget *parent) :
		MvQMainWindow(parent),
		data_ (0),
		gpModel_ (0),
		actionFileInfo_ (0),
		treeData_ (0), ignoreDataRowSpinChangeSignal_(false)
{
	// 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)
	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->setObjectName(QString::fromUtf8("vboxLayout"));
	mainLayout->setContentsMargins(0,0,0,0);
	mainLayout->setSpacing(1);
    QWidget* w = new QWidget(this);
	w->setLayout(mainLayout);
	mainSplitter_->addWidget(w);

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

    // 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()
{
	// Save settings
	writeSettings();

	// Clean memory
	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
    QAction *actionAbout = new QAction(this);
    actionAbout->setObjectName(QString::fromUtf8("actionAbout"));
    QIcon icon;
    icon.addPixmap(QPixmap(QString::fromUtf8(":/window/metview_logo")), QIcon::Normal, QIcon::Off);
    actionAbout->setIcon(icon);
    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
	QVBoxLayout* dataLayout = new QVBoxLayout;
	dataLayout->setContentsMargins(0,0,0,0);
    dataPanel_ = new QWidget(this);
	dataPanel_->setLayout(dataLayout);

    // Combo box for index selection
    QWidget *gotoW=new QWidget(this);
    gotoW->setProperty("headerStyle","1");
    dataLayout->addWidget(gotoW);

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

    QLabel *messageTitleLab=new QLabel(tr("&Row:"),this);
    messageTitleLab->setProperty("headerStyle","1");
    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);

	// Build a tree to show the meta data
	treeData_ = new MvQTreeView;
	treeData_->setObjectName("geopTreeData");
	treeData_->setProperty("mvStyle",0);
	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 string& filename )
{
	// Clean metadata if already exists
	if ( data_ )
	{
		delete data_;
		data_ = 0;
	}

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

	// Initialize netcdf metadata object
	data_ = new MvGeoPoints();
	bool ok = data_->load( filename.c_str() );

	// Update File info label
	updateFileInfoLabel();

	// Check if it is a valid geopoints file
	if ( !ok )
	{
		delete data_;
		data_ = 0;
        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_->setData(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::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("ECMWF","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("ECMWF","MV4-GeopExaminer");

	QVariant value;
	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();
}
