/***************************** 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 "MvGeoPoints.h"
#include "MvQAbout.h"
#include "MvQFileInfoLabel.h"
#include "MvGeoPointsModel.h"
#include "MvQLogBrowser.h"
#include "MvQSearchLinePanel.h"
#include "MvQTreeView.h"
#include "MvQTreeViewSearchLine.h"

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();
	setupLogArea();

	// 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;
	w->setLayout(mainLayout);
	mainSplitter_->addWidget(w);
//?	mainSplitter_->setCollapsible(1,false);

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

	// Central tab
	metaTab_= new QTabWidget;	
	mainLayout->addWidget(metaTab_,1);

	metaTab_->addTab(dataPanel_,tr("Meta data"));	
	mainLayout->addWidget(findPanel_);
	mainSplitter_->addWidget(logPanel_);

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

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

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

	// Signals and slots
	connect(this,SIGNAL(statusMessage(QString)),
		this,SLOT(slotStatusMessage(QString)));

	// Setup previous main layout
	readSettings();
}
 
GeopExaminer::~GeopExaminer()
{
	// Save settings
	writeSettings();

	// Clean memory
	delete data_;
	delete gpModel_;
}


void GeopExaminer::setupEditActions()
{
	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));
}

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/fileInfo.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;
	dataPanel_->setLayout(dataLayout);

	// Combo box for index selection
	QLabel *spinLabel = new QLabel(tr("Go to row:"));
	dataRowSpin_ = new QSpinBox;
	spinLabel->setBuddy(dataRowSpin_);
	QHBoxLayout* msgSpinLayout = new QHBoxLayout;
	msgSpinLayout->addWidget(spinLabel);
	msgSpinLayout->addWidget(dataRowSpin_);
	msgSpinLayout->addStretch(1);
	dataLayout->addLayout(msgSpinLayout);
	
	// Signals and slots
	connect(dataRowSpin_, SIGNAL(valueChanged(int)),
		this, SLOT(slotDataRowSpinChanged(int)));
		
	// Instantiate the model
	gpModel_ = new MvQGeoPointsDataModel;

	// Instantiate the sort model
	gpSortModel_= new QSortFilterProxyModel;
	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()
{	
	dataFind_= new MvQTreeViewSearchLine(treeData_,1,"");

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

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

	// Write inicial message in the log area
	LogItem *log = new LogItem;
	LogHandler::instance()->add(log);
	log->description("Loading file");
	log->method("MvGeoPoints API");

	// 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;
		log->error("Could not open geopoints file");
		slotUpdateLogOutput();
		QString buf = tr("<b>Status: </b><font color=red>FAILED</font>");
		emit statusMessage(buf);
		return false;
	}
	slotUpdateLogOutput();
	QString buf = tr("<b>Status:</b> <font color=green>OK</font>");
	emit statusMessage(buf);

	// 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());

#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::slotUpdateLogOutput()
{
	logBrowser_->update();
}

void GeopExaminer::slotClearLog(bool)
{
	LogHandler::instance()->clear();
	logBrowser_->clear();
}

void GeopExaminer::slotStatusMessage(QString s)
{
	statusMessageLabel_->setText(s);
}

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::setupLogArea()
{
	// Log Area
	QVBoxLayout *logLayout = new QVBoxLayout;
	logLayout->setObjectName(QString::fromUtf8("vboxLayout"));
	logLayout->setContentsMargins(0,0,0,0);
	logLayout->setSpacing(1);
	logPanel_= new QWidget;
	logPanel_->setMinimumHeight(100);
	logPanel_->setLayout(logLayout);
	//mainSplitter_->addWidget(logPanel_);

	// Define header layout
	QHBoxLayout *hb = new QHBoxLayout;
	hb->setContentsMargins(0,0,0,0);
	logLayout->addLayout(hb);

	// Add label to the header
	QLabel* label = new QLabel(tr("Log"));
	label->setFrameShape(QFrame::StyledPanel);
	hb->addWidget(label,1);

	// Add Clear button to the header
	QPushButton *clearPb = new QPushButton(tr("Clear log"));
	hb->addWidget(clearPb);

	// Log browser
	logBrowser_= new MvQLogBrowser(logLayout);

	// Signals and slots
	connect ( clearPb,SIGNAL(clicked(bool)), this,SLOT(slotClearLog(bool)) );
}

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);
		ignoreDataRowSpinChangeSignal_=false;
	}
}  

void GeopExaminer::writeSettings()
{
	QSettings settings("ECMWF","MV4-GeopExaminer");
	
	settings.beginGroup("mainWindow");
	settings.setValue("geometry",saveGeometry());
//	settings.setValue("centralSplitter",centralSplitter_->saveState());
	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());
//	centralSplitter_->restoreState(settings.value("centralSplitter").toByteArray());
	mainSplitter_->restoreState(settings.value("mainSplitter").toByteArray());
	
	if(settings.value("actionFileInfoStatus").isNull())
		actionFileInfo_->setChecked(true);
	else
		actionFileInfo_->setChecked(settings.value("actionFileInfoStatus").toBool());

	settings.endGroup();
}
