/***************************** 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 <QApplication>
#include <QAction>
#include <QCloseEvent>
#include <QComboBox>
#include <QCursor>
#include <QDebug>
#include <QFile>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QSettings>
#include <QSpinBox>
#include <QSplitter>
#include <QStackedWidget>
#include <QStatusBar>
#include <QString>
#include <QStringList>
#include <QTextBrowser>
#include <QVBoxLayout>

#include "GribExaminer.h"

#include "GribMetaData.h"
#include "MvKeyProfile.h"

#include "MvQAbout.h"
#include "MvQFileInfoLabel.h"
#include "MvQGribDumpModel.h"
#include "MvQKeyProfileModel.h"
#include "MvQKeyProfileTree.h"
#include "MvQTextEditSearchLine.h"
#include "MvQTreeView.h"
#include "MvQTreeViewSearchLine.h"

GribExaminer::GribExaminer(string &tmpfilename, QWidget *parent) : MvQAbstractMessageExaminer("GribExaminer",parent)
{	
	setAttribute(Qt::WA_DeleteOnClose);

	setWindowTitle("Metview - Grib Examiner");

	//Initial size
	setInitialSize(1100,800);

	//Init
	messageType_="GRIB";

	gribNameSpace_ << "Default" << "geography" << "ls" << "mars" 
			<< "parameter" << "statistics" << "time" << "vertical";

	mvDumpModel_=0;
	stdDumpModel_=0;
	wmoDumpModel_=0;
	valueDumpModel_=0;

	fileInfoLabelNeedsUpdating_=true;
	ignoreValueRowSpinChangeSignal_=false;

	tmpfilename_ = tmpfilename;

	//Set up grib dump boxes
	setupDumpBox();

	//Build ui

	QWidget *w;

	//----------------------
	// 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);
	w=new QWidget;
	w->setLayout(mainLayout);
	mainSplitter_->addWidget(w);

	//------------------
	// File info label
	//------------------
      
 	//Add to layout 
	mainLayout->addWidget(fileInfoLabel_);

	//---------------------
	// Central splitter
	//---------------------

	centralSplitter_ = new QSplitter(this); 
	centralSplitter_->setOpaqueResize(false);	
	mainLayout->addWidget(centralSplitter_,1);

	//-------------------------
	// Populate central splitter
	//-------------------------
	
	centralSplitter_->addWidget(messagePanel_);
	centralSplitter_->addWidget(dumpPanel_);

	//--------------------------
	// Find widget
	//--------------------------
	
	mainLayout->addWidget(findPanel_);
	
	//--------------------------
	// Log Area
	//--------------------------

	mainSplitter_->addWidget(logPanel_);
	mainSplitter_->setCollapsible(1,false);

	//----------------------------
	// 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'
	
	connect(this,SIGNAL(statusMessage(QString)),
		this,SLOT(slotStatusMessage(QString)));
	
	//-------------------------
	// Settings
	//-------------------------
	
	readSettings();
}
 
GribExaminer::~GribExaminer()
{	
	writeSettings();
	
	if(mvDumpModel_) delete mvDumpModel_;
	if(stdDumpModel_) delete stdDumpModel_;
	if(wmoDumpModel_) delete wmoDumpModel_;
	if(valueDumpModel_) delete valueDumpModel_;	
}

void GribExaminer::closeEvent (QCloseEvent * event)
{
	close();
	event->accept();
}


void GribExaminer::setupDumpBox()
{
	dumpPanel_=new QWidget;
	QVBoxLayout *dumpLayout = new QVBoxLayout;
	dumpLayout->setContentsMargins(0,0,0,0);
	dumpPanel_->setLayout(dumpLayout);	

	//------------------------------
	// Dump combo
	//------------------------------
	
	QHBoxLayout *dumpComboLayout=new  QHBoxLayout;

	//Combo box for key profile selection
	QLabel *dumpLabel = new QLabel(tr("Dump mode:"));
	dumpCombo_ = new QComboBox;
	dumpLabel->setBuddy(dumpCombo_);

	dumpComboLayout->addWidget(dumpLabel);
	dumpComboLayout->addWidget(dumpCombo_);
	dumpComboLayout->addStretch(1);
		
	dumpCombo_->addItem(tr("Namespace"));
	dumpCombo_->addItem(tr("Standard"));
	dumpCombo_->addItem(tr("Values"));
	dumpCombo_->addItem(tr("WMO-style"));
	dumpCombo_->setCurrentIndex(-1);
	
	dumpLayout->addLayout(dumpComboLayout);

	//---------------------------------
	// Stacked widget for dump modes
	//---------------------------------

	dumpStacked_ = new QStackedWidget;
	dumpLayout->addWidget(dumpStacked_);

	//---------------------------------
	// Mv dump
	//--------------------------------
		
	//Layout
	QVBoxLayout *mvDumpLayout=new QVBoxLayout;	
	QWidget *w = new QWidget;
	w->setLayout(mvDumpLayout);
	dumpStacked_->addWidget(w);

	QHBoxLayout *nsComboLayout=new  QHBoxLayout;

	QLabel *nsLabel = new QLabel(tr("GRIB API Namespace:"));
	nsCombo_ = new QComboBox;
	nsLabel->setBuddy(nsCombo_);

	nsComboLayout->addWidget(nsLabel);
	nsComboLayout->addWidget(nsCombo_);
	nsComboLayout->addStretch(1);

	nsCombo_->addItems(gribNameSpace_);
	nsCombo_->setCurrentIndex(-1);
	mvDumpLayout->addLayout(nsComboLayout);

	//Message tree
	mvDumpModel_= new MvQGribMvDumpModel;
	mvDumpSortModel_= new QSortFilterProxyModel;
        mvDumpSortModel_->setSourceModel(mvDumpModel_);
	mvDumpSortModel_->setDynamicSortFilter(true);
	mvDumpSortModel_->setFilterRole(Qt::UserRole);
	//messageSortModel_->setFilterRegExp(QRegExp("[1]"));
	mvDumpSortModel_->setFilterFixedString("1");
	mvDumpSortModel_->setFilterKeyColumn(0);

	mvDumpTree_= new MvQTreeView;
	mvDumpTree_->setObjectName("mvDumpTree");
	mvDumpTree_->setProperty("mvStyle",1);
	mvDumpTree_->setSortingEnabled(true);
	mvDumpTree_->sortByColumn (0,Qt::AscendingOrder); 
	mvDumpTree_->setAlternatingRowColors(true);
	mvDumpTree_->setAllColumnsShowFocus(true);
	mvDumpTree_->setModel(mvDumpSortModel_);
	mvDumpTree_->setRootIsDecorated(false);

	mvDumpTree_->setDragDropMode(QAbstractItemView::DragOnly);

	mvDumpLayout->addWidget(mvDumpTree_);
	
	mvDumpSearch_= new MvQTreeViewSearchLine(mvDumpTree_,0,"");
	findPanel_->addSearchLineToRight(mvDumpSearch_,w);
		
	//---------------------------------
	// Std dump
	//--------------------------------

	//Tab
	stdDumpTab_ = new QTabWidget;	
	//stdDumpLayout->addWidget(stdTab);
	dumpStacked_->addWidget(stdDumpTab_);

	stdDumpTree_= new MvQTreeView;
	stdDumpModel_= new MvQGribStdDumpModel;
	stdDumpTree_->setModel(stdDumpModel_);
	stdDumpTree_->setObjectName("stdDumpTree");
	stdDumpTree_->setProperty("mvStyle",1);
	stdDumpTree_->setAlternatingRowColors(true);
	stdDumpTree_->setAllColumnsShowFocus(true);
	stdDumpTree_->setDragDropMode(QAbstractItemView::DragOnly);
	
	stdDumpTab_->addTab(stdDumpTree_,tr("Tree view"));

	stdDumpBrowser_=new QTextBrowser;
	stdDumpBrowser_->setProperty("mvStyle","fileContents");
	stdDumpTab_->addTab(stdDumpBrowser_,tr("Plain text"));

	stdDumpSearch_= new MvQTreeViewSearchLine(stdDumpTree_,0,"");
	findPanel_->addSearchLineToRight(stdDumpSearch_,stdDumpTree_);

	stdDumpTextSearch_= new MvQTextEditSearchLine(stdDumpBrowser_,"");
	findPanel_->addSearchLineToRight(stdDumpTextSearch_,stdDumpBrowser_);

	connect(stdDumpTab_,SIGNAL(currentChanged(int)),
		this,SLOT(slotCurrentStdDumpChanged(int)));
		
	//---------------------------------	
	// Value dump
	//--------------------------------

	QVBoxLayout *valueDumpLayout=new QVBoxLayout;	
	w=new QWidget();
	w->setLayout(valueDumpLayout);
		
	//Spin box for index selection
	QLabel *spinLabel = new QLabel(tr("Go to row:"));
	valueRowSpin_ = new QSpinBox;
	spinLabel->setBuddy(valueRowSpin_);
	QHBoxLayout* valueSpinLayout = new QHBoxLayout;
	valueSpinLayout->addWidget(spinLabel);
	valueSpinLayout->addWidget(valueRowSpin_);
			
	valueDumpLabel_= new QLabel;
	valueSpinLayout->addWidget(valueDumpLabel_);
	valueSpinLayout->addStretch(1);	
	
	valueDumpLayout->addLayout(valueSpinLayout);
	
	// Signals and slots
	connect(valueRowSpin_, SIGNAL(valueChanged(int)),
		this, SLOT(slotValueRowSpinChanged(int)));
	
	valueDumpModel_= new MvQGribValueDumpModel;
	valueDumpSortModel_= new QSortFilterProxyModel;
        valueDumpSortModel_->setSourceModel(valueDumpModel_);
	valueDumpSortModel_->setDynamicSortFilter(true);
	valueDumpSortModel_->setSortRole(Qt::UserRole);
	
	valueDumpTree_= new MvQTreeView;
	valueDumpTree_->setObjectName("valueDumpTree");
	valueDumpTree_->setProperty("mvStyle",1);
	valueDumpTree_->setSortingEnabled(true);
	valueDumpTree_->sortByColumn (0,Qt::AscendingOrder);
	valueDumpTree_->setAlternatingRowColors(true);
	valueDumpTree_->setAllColumnsShowFocus(true);
	valueDumpTree_->setModel(valueDumpSortModel_);
	valueDumpTree_->setRootIsDecorated(false);
	valueDumpTree_->setUniformRowHeights(true);
	valueDumpTree_->setActvatedByKeyNavigation(true);
	
	valueDumpLayout->addWidget(valueDumpTree_);
	
	connect(valueDumpTree_,SIGNAL(clicked(QModelIndex)),
		this,SLOT(slotSelectValueRow(QModelIndex)));

	connect(valueDumpTree_,SIGNAL(activated(const QModelIndex&)),
		this,SLOT(slotSelectValueRow(const QModelIndex&)));
	
	dumpStacked_->addWidget(w);

	valueDumpSearch_= new MvQTreeViewSearchLine(valueDumpTree_,0,"");
	findPanel_->addSearchLineToRight(valueDumpSearch_,valueDumpTree_);

	//---------------------------------	
	// Wmo dump
	//--------------------------------
	
	//Tab
	wmoDumpTab_ = new QTabWidget;	
	//wmoDumpLayout->addWidget(wmoTab);
	dumpStacked_->addWidget(wmoDumpTab_);

	wmoDumpTree_= new MvQTreeView;
	wmoDumpModel_= new MvQGribWmoDumpModel;
	wmoDumpTree_->setModel(wmoDumpModel_);
	wmoDumpTree_->setObjectName("wmoDumpTree");
 	wmoDumpTree_->setProperty("mvStyle",1);
	wmoDumpTree_->setAlternatingRowColors(true);
	wmoDumpTree_->setAllColumnsShowFocus(true);	
	
	wmoDumpTree_->setDragDropMode(QAbstractItemView::DragOnly);
	wmoDumpTree_->setColumnToDrag(1);;

	wmoDumpTab_->addTab(wmoDumpTree_,tr("Tree view"));

	wmoDumpBrowser_=new QTextBrowser;
	wmoDumpBrowser_->setProperty("mvStyle","fileContents");
	wmoDumpTab_->addTab(wmoDumpBrowser_,tr("Plain text"));

	wmoDumpSearch_= new MvQTreeViewSearchLine(wmoDumpTree_,1,"");
	findPanel_->addSearchLineToRight(wmoDumpSearch_,wmoDumpTree_);

	wmoDumpTextSearch_= new MvQTextEditSearchLine(wmoDumpBrowser_,"");
	findPanel_->addSearchLineToRight(wmoDumpTextSearch_,wmoDumpBrowser_);

	connect(wmoDumpTab_,SIGNAL(currentChanged(int)),
		this,SLOT(slotCurrentWmoDumpChanged(int)));			
	
	//Search
	//QHBoxLayout *wmoSearchLayout = new QHBoxLayout;	
	//wmoDumpSearch_ = new MvQSearchLineBase(wmoSearchLayout,tr("Search for key:"));
	//wmoDumpLayout->addLayout(wmoSearchLayout );
}

void GribExaminer::initDumps()
{
	//Init dump combo
	int currentIndex=dumpCombo_->currentIndex();
	if(currentIndex == -1) currentIndex=3; //Default is wmo-dump
	dumpCombo_->setCurrentIndex(-1);

	connect(dumpCombo_, SIGNAL(currentIndexChanged(int)),
                dumpStacked_, SLOT(setCurrentIndex(int)));
	
	connect(dumpCombo_, SIGNAL(currentIndexChanged(int)),
                this, SLOT(slotChangeCurrentDump(int)));

	dumpCombo_->setCurrentIndex(currentIndex);

	//Init ns combo
	currentIndex=nsCombo_->currentIndex();
	if(currentIndex == -1) currentIndex=2; //Default is namesapce "ls"
	nsCombo_->setCurrentIndex(-1);

	connect(nsCombo_, SIGNAL(currentIndexChanged(const QString&)),
                this, SLOT(slotSetGribNameSpace(const QString &)));

	connect(nsCombo_, SIGNAL(currentIndexChanged(const QString&)),
                this, SLOT(slotSetGribNameSpace(const QString &)));

	nsCombo_->setCurrentIndex(currentIndex);
	
	/*//Synchronize the dump mode		
	if(dumpCombo_->currentIndex() == 0)
	{
		dumpStacked_->setCurrentIndex(0);
	}
	dumpCombo_->setCurrentIndex(0);*/

	//Set tree focus
	wmoDumpTree_->setFocus(Qt::OtherFocusReason);
}

void GribExaminer::initAllKeys()
{
	//Get all keys
	MvKeyProfile *prof=new MvKeyProfile("Metview keys");
	prof->addKey(new MvKey("MV_Index","Index","Message index"));
	allKeys_ << prof;

	GribMetaData *grib=static_cast<GribMetaData*>(data_);

	foreach(QString ns,gribNameSpace_)
	{
		QString pname="Namespace: " + ns;
		MvKeyProfile *prof=new MvKeyProfile(pname.toStdString());
		grib->getKeyList(1,ns.toStdString().c_str(),prof);
		allKeys_ << prof;
	}		
}



void GribExaminer::loadDumps()
{
	//At this point the first message scan has finished so we know the real  message
	//number. It is not known at the beginning because for multi message fields
	//grib_count_in_file thta we use to estimate the message number does not 
	//count the sub messages. So we need to updeate the file info label now.
	if(fileInfoLabelNeedsUpdating_)
	{
	  	updateFileInfoLabel();
		fileInfoLabelNeedsUpdating_=false;
	}	
	
	//Save the expand state of the current wmoDumpTree
	QModelIndexList indexLst=wmoDumpModel_->match(wmoDumpModel_->index(0,0),
			    Qt::DisplayRole,"*",-1,
		            Qt::MatchWildcard | Qt::MatchRecursive);
	
	QModelIndexList expandLst;
	foreach(QModelIndex index,indexLst)
	{
		if(wmoDumpTree_->isExpanded(index))
			expandLst << index;
	}	

	mvDumpLoaded_=false;
	wmoDumpLoaded_=false;
	stdDumpLoaded_=false;
	
	//Unload value dump
	GribValueDump* valueDump=valueDumpModel_->dumpData();
	if(valueDump) 
	{
		valueDumpModel_->dataIsAboutToChange();
		valueDumpModel_->setDumpData(0);
		delete valueDump;
	}	
	valueDumpLoaded_=false;

	//Generate and read grib dumps
	switch(dumpCombo_->currentIndex())
	{
	case 0:
		loadMvDump();
		break;
	case 1:
		loadStdDump();
		break;
	case 2:
		loadValueDump();
		break;
	case 3:
		loadWmoDump();
		break;
	default:
		break;
	}

	//Try to restore the expand state of the wmoDumpTree
	foreach(QModelIndex index,expandLst)
	{
		if(wmoDumpModel_->hasChildren(index))
		{
			wmoDumpTree_->setExpanded(index,true);
		}
	}	
}


void GribExaminer::slotSetGribNameSpace(const QString &ns)
{
	if(mvDumpModel_)
		mvDumpModel_->setGribNameSpace(ns);
}


void GribExaminer::loadMvDump()
{	
	if(mvDumpLoaded_) 
		return;

	slotStatusMessage(tr("Load namespace dump ..."));

	int cnt=currentMessageNo_;

	GribMvDump* currentDump=mvDumpModel_->dumpData();

	//Generate and read grib dump
	GribMvDump* dump = new GribMvDump(tmpfilename_);
	dump->read(data_->fileName(),data_->unfilteredMessageCnt(cnt));	

	mvDumpModel_->dataIsAboutToChange();
	mvDumpModel_->setDumpData(dump);

	for(int i=0;i < mvDumpModel_->columnCount()-1; i++)
	{ 
		mvDumpTree_->resizeColumnToContents(i);
	}

	if(currentDump != 0)
		delete currentDump;

	mvDumpLoaded_=true;
}


void GribExaminer::loadWmoDump()
{	
	if(wmoDumpLoaded_) 
		return;

	slotStatusMessage(tr("Load wmo dump ..."));

	int cnt=currentMessageNo_;

	GribWmoDump* currentDump=wmoDumpModel_->dumpData();

	//Generate and read grib dump
	GribWmoDump* dump = new GribWmoDump(tmpfilename_);
	dump->read(data_->fileName(),data_->unfilteredMessageCnt(cnt));	

	wmoDumpModel_->dataIsAboutToChange();
	wmoDumpModel_->setDumpData(dump);

	for(int i=0;i < wmoDumpModel_->columnCount()-1; i++)
	{ 
		wmoDumpTree_->resizeColumnToContents(i);
	}

       	wmoDumpBrowser_->setPlainText(QString(dump->text().c_str()));

	if(currentDump != 0)
		delete currentDump;

	wmoDumpLoaded_=true;
}

void GribExaminer::loadStdDump()
{		
	if(stdDumpLoaded_) 
		return;

	slotStatusMessage(tr("Load default dump ..."));

	int cnt=currentMessageNo_;

	GribStdDump* currentDump=stdDumpModel_->dumpData();

	//Generate and read grib dump
	GribStdDump* dump = new GribStdDump(tmpfilename_);
	dump->read(data_->fileName(),data_->unfilteredMessageCnt(cnt));	

	stdDumpModel_->dataIsAboutToChange();
	stdDumpModel_->setDumpData(dump);

	for(int i=0;i < stdDumpModel_->columnCount()-1; i++)
	{ 
		stdDumpTree_->resizeColumnToContents(i);
	}
	
	// Text view for the dump
        stdDumpBrowser_->setPlainText(QString(dump->text().c_str()));

	if(currentDump != 0)
		delete currentDump;

	stdDumpLoaded_=true;
}

void GribExaminer::loadValueDump()
{		
	if(valueDumpLoaded_) 
		return;

	slotStatusMessage(tr("Load value dump ..."));

	int cnt=currentMessageNo_;

	GribValueDump* currentDump=valueDumpModel_->dumpData();

	//Generate and read grib dump
	GribValueDump* dump = new GribValueDump;
	dump->read(data_->fileName(),data_->unfilteredMessageCnt(cnt));	

	valueDumpModel_->dataIsAboutToChange();
	valueDumpModel_->setDumpData(dump);

	for(int i=0;i < valueDumpModel_->columnCount()-1; i++)
	{ 
		valueDumpTree_->resizeColumnToContents(i);
	}
	
	// Set min/max values for spinbox
	valueRowSpin_->setRange(1,dump->num());
	
	//Update info
	QString info=" (Number of points: " + QString::number(dump->num()) + ")";
	//info+="  <b>Average:</b> " + QString::number(dump->average());
	//info+="  <b>Stdev:</b> " + QString::number(dump->stdev());
	//info+=" <b>Skewness:</b> " + QString::number(dump->skewness()); 
	//info+=" <b>Kurtosis:</b> " + QString::number(dump->kurtosis());
	
	valueDumpLabel_->setText(info);
	
	if(currentDump != 0)
		delete currentDump;

	valueDumpLoaded_=true;
}


void GribExaminer::slotChangeCurrentDump(int index)
{
	//Generate and read grib dumps
	switch(index)
	{
	case 0:
		loadMvDump();
		break;
	case 1:
		loadStdDump();
		break;
	case 2:
		loadValueDump();
		break;	
	case 3:
		loadWmoDump();
		break;		
	default:
		break;
	}

	emit logOutputChanged();

	dumpStacked_->setCurrentIndex(index);
	
	switch(index)
	{
	case 0:
		findPanel_->setCurrentSearchLineById(dumpStacked_->widget(index));
		break;
	case 1:
		slotCurrentStdDumpChanged(stdDumpTab_->currentIndex());
		break;
	case 2:
		findPanel_->setCurrentSearchLineById(valueDumpTree_);
		break;
	case 3:
		slotCurrentWmoDumpChanged(wmoDumpTab_->currentIndex());
		break;
	default:
		break;
	}
	
	
}

void GribExaminer::slotCurrentStdDumpChanged(int index)
{
	findPanel_->setCurrentSearchLineById(stdDumpTab_->widget(index));
} 
  
void GribExaminer::slotCurrentWmoDumpChanged(int index)
{
	findPanel_->setCurrentSearchLineById(wmoDumpTab_->widget(index));
} 

void GribExaminer::slotValueRowSpinChanged(int rowNumber)
{
	if(ignoreValueRowSpinChangeSignal_)
		return;
	
	QModelIndex srcIndex = valueDumpModel_->index(rowNumber-1,0);
	valueDumpTree_->setCurrentIndex(valueDumpSortModel_->mapFromSource(srcIndex));
}

void GribExaminer::slotSelectValueRow(const QModelIndex &index)
{
	QModelIndex srcIndex=valueDumpSortModel_->mapToSource(index);
	
  	int cnt=valueDumpModel_->data(valueDumpModel_->index(srcIndex.row(),0)).toInt();
	if(cnt > 0)
	{
		ignoreValueRowSpinChangeSignal_=true;
		valueRowSpin_->setValue(cnt);
		ignoreValueRowSpinChangeSignal_=false;
	}
}  


void GribExaminer::slotShowAboutBox()
{
	MvQAbout about("GribExaminer","",MvQAbout::GribApiVersion | MvQAbout::MetviewVersion);
	about.exec();
}

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

void GribExaminer::updateFileInfoLabel()
{
	GribMetaData *grib=static_cast<GribMetaData*>(data_);
	
	fileInfoLabel_->setGribTextLabel(QString(data_->fileName().c_str()),data_->totalMessageNum(),
					 data_->isFilterEnabled(),data_->messageNum(),grib->hasMultiMessage());
}

void GribExaminer::writeSettings()
{
	QSettings settings("ECMWF","MV4-GribExaminer");
	
	settings.beginGroup("mainWindow");
	settings.setValue("geometry",saveGeometry());
	settings.setValue("centralSplitter",centralSplitter_->saveState());
	settings.setValue("mainSplitter",mainSplitter_->saveState());
	settings.endGroup();
	
	settings.beginGroup("GribExaminer");
	settings.setValue("actionFileInfoStatus",actionFileInfo_->isChecked());
	settings.setValue("keyProfileName",keyCombo_->currentText());
	settings.setValue("dumpMode",dumpCombo_->currentText());
	settings.setValue("gribNameSpace",nsCombo_->currentText());
	settings.setValue("stdDumpTabIndex",stdDumpTab_->currentIndex());
	settings.setValue("wmoDumpTabIndex",wmoDumpTab_->currentIndex());
	settings.setValue("actionLogStatus",actionLog_->isChecked());
	settings.endGroup();
}

void GribExaminer::readSettings()
{
	QVariant value;

	QSettings settings("ECMWF","MV4-GribExaminer");
	
	settings.beginGroup("mainWindow");
	restoreGeometry(settings.value("geometry").toByteArray());
	centralSplitter_->restoreState(settings.value("centralSplitter").toByteArray());
	mainSplitter_->restoreState(settings.value("mainSplitter").toByteArray());

	settings.endGroup();


	settings.beginGroup("GribExaminer");

	QString txt; 
	int ival;

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

	if(settings.value("actionLogStatus").isNull())
	{
		//By default it should be false
		actionLog_->setChecked(false);
	}
	else
	{
		actionLog_->setChecked(settings.value("actionLogStatus").toBool());
	}

	//Init key combo
	//It is empty at this stage!!
	savedKeyProfileName_=settings.value("keyProfileName").toString();
	/*for(int i=0; i < keyCombo_->count(); i++)
	{
		if(keyCombo_->itemText(i) == txt)
		{
			keyCombo_->setCurrentIndex(i);
			break;
		}
	}*/

	//Init dump combo
	txt=settings.value("dumpMode").toString();
	for(int i=0; i < dumpCombo_->count(); i++)
	{
		if(dumpCombo_->itemText(i) == txt)
		{
			dumpCombo_->setCurrentIndex(i);
			break;
		}
	}

	//Init grib namsepace
	txt=settings.value("gribNameSpace").toString();
	for(int i=0; i < nsCombo_->count(); i++)
	{
		if(nsCombo_->itemText(i) == txt)
		{
			nsCombo_->setCurrentIndex(i);
			break;
		}
	}
	
	//Init tabs
	ival=settings.value("stdDumpTabIndex").toInt();
	stdDumpTab_->setCurrentIndex(ival);

	//Init tabs
	ival=settings.value("wmoDumpTabIndex").toInt();
	wmoDumpTab_->setCurrentIndex(ival);


	settings.endGroup();
}
