/***************************** 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 <QComboBox>
#include <QCursor>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QInputDialog>
#include <QLineEdit>
#include <QMessageBox>
#include <QProgressDialog>
#include <QPushButton>
#include <QSettings>
#include <QSortFilterProxyModel>
#include <QSplitter>
#include <QStackedLayout>
#include <QStackedWidget>
#include <QString>
#include <QStringList>
#include <QTextBrowser>
#include <QTreeView>
#include <QVBoxLayout>

#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdio>
#include <stdio.h>
#include <stdlib.h>

#include "MvQAbstractMessageExaminer.h"

#include "MvKeyProfile.h"
#include "MvVersionInfo.h"
#include "LogHandler.h"

#include "MvQKeyDialog.h"
#include "MvQFileInfoLabel.h"
#include "MvQKeyManager.h"
#include "MvQKeyProfileModel.h"
#include "MvQKeyProfileTree.h"
#include "MvQLogBrowser.h"
#include "MvQMainWindow.h"
#include "MvQTreeViewSearchLine.h"
#include "MvQTreeView.h"

MvQAbstractMessageExaminer::MvQAbstractMessageExaminer(QString appName,QWidget *parent) : MvQMainWindow(parent), appName_(appName)
{
	//File info label        
	fileInfoLabel_=new MvQFileInfoLabel();

	messageModel_=0;
	dumpPanel_=0;
	tmpProfile_=0;
	
	//Set up message group box
	setupMessageBox();
	
	//Set up dump group box
	//setupDumpBox();

	//Set up find panel 
	setupFindBox();

	//Set up log area 
	setupLogBox();

	//----------------------
	// Init
	//----------------------

	currentMessageNo_=-1;

	//----------------------------
	// Signals and slots
	//----------------------------

	setupEditMenu();
	setupViewMenu();
	setupSettingsMenu();
	setupProfilesMenu();
	setupHelpMenu();

	//----------------------------
	// Signals and slots
	//----------------------------

	//Message list selection	
	connect(messageTree_,SIGNAL(clicked(QModelIndex)),
		this,SLOT(slotSelectMessage(QModelIndex)));

	connect(messageTree_,SIGNAL(activated(QModelIndex)),
		this,SLOT(slotSelectMessage(QModelIndex)));

	connect(messageTree_,SIGNAL(profileChanged(bool)),
		this,SLOT(slotProfileChanged(bool)));

	connect(messageModel_,SIGNAL(keyInserted()),
		this,SLOT(slotReloadProfile()));
	
}
 
MvQAbstractMessageExaminer::~MvQAbstractMessageExaminer()
{	
	if(messageModel_) delete messageModel_;
	if(tmpProfile_) delete tmpProfile_;
	keyManager_->saveProfiles();
}

void MvQAbstractMessageExaminer::close()
{
	saveProfileBeforeAction(false);
}

void MvQAbstractMessageExaminer::setupMessageBox()
{
	//--------------------------------
	// Message tree (key profile)
	//--------------------------------

	messagePanel_=new QWidget;
	messageLayout_ = new QVBoxLayout;
	messageLayout_->setContentsMargins(0,0,0,0);
	messagePanel_->setLayout(messageLayout_);
	//messageSplitter_->addWidget(messageWidget);	

	//Label
	//label=new QLabel(tr("Messages"));
	//label->setFrameShape(QFrame::StyledPanel);
	//label->setProperty("mvStyle","panel");
	//messageLayout_->addWidget(label);

	//Message tree
	messageModel_= new MvQKeyProfileModel;
	messageSortModel_= new MvQKeyProfileSortFilterModel;
        messageSortModel_->setSourceModel(messageModel_);
	messageSortModel_->setDynamicSortFilter(true);
	messageSortModel_->setFilterRole(Qt::UserRole);
	//messageSortModel_->setFilterRegExp(QRegExp("[1]"));
	messageSortModel_->setFilterFixedString("1");
	messageSortModel_->setFilterKeyColumn(0);

	messageTree_=new MvQKeyProfileTree(messageModel_,messageSortModel_);
	messageTree_->setUniformRowHeights(true);

	messageLayout_->addWidget(messageTree_);	
}

void MvQAbstractMessageExaminer::setupFindBox()
{	
	messageFind_= new MvQTreeViewSearchLine(messageTree_,1,"");
	//connect(messageModel_,SIGNAL(modelReset()),
	//	messageFind_,SLOT(slotUpdateColumns()));

	findPanel_=new MvQDualSearchLinePanel;
	findPanel_->addSearchLineToLeft(messageFind_,messageTree_);
	findPanel_->hide();

}

void MvQAbstractMessageExaminer::setupLogBox()
{	
	QVBoxLayout *logLayout = new QVBoxLayout;
        logLayout->setObjectName(QString::fromUtf8("vboxLayout"));
	logLayout->setContentsMargins(0,0,0,0);
	logLayout->setSpacing(1);

	logPanel_=new QWidget;
	logPanel_->setMinimumHeight(110);
	logPanel_->setLayout(logLayout);
	
	QHBoxLayout *hb = new QHBoxLayout;
	hb->setContentsMargins(0,0,0,0);
	logLayout->addLayout(hb);

	//Label
	QLabel *label = new QLabel(tr("Log"));
	label->setFrameShape(QFrame::StyledPanel);
	label->setProperty("mvStyle","panel");

	//QLabel *label1 = new QLabel();
	//label1->setPixmap(QPixmap(QString::fromUtf8(":/examiner/log.png")).scaled(16,16));

	//hb->addWidget(label1);
	hb->addWidget(label,1);

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

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

	connect(clearPb,SIGNAL(clicked(bool)),
		this,SLOT(slotClearLog(bool)));

	connect(this,SIGNAL(logOutputChanged()),
		this,SLOT(slotUpdateLogOutput()));
}
	
/*void MvQAbstractMessageExaminer::setupDumpBox()
{
	dumpPanel_=new QWidget;
	QVBoxLayout *dumpLayout = new QVBoxLayout;
	dumpLayout->setContentsMargins(0,0,0,0);
	dumpPanel_->setLayout(dumpLayout);	

	//Title
	QLabel *titleLabel=new QLabel(tr("Meta data of the selected message"));
	titleLabel->setFrameShape(QFrame::StyledPanel);
	dumpLayout->addWidget(titleLabel);
}*/


void MvQAbstractMessageExaminer::setupViewMenu()
{
	//
	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);	

	//Define routines
	connect(actionFileInfo_,SIGNAL(toggled(bool)),
		fileInfoLabel_,SLOT(setVisible(bool)));

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

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

	//Log is hidden by default!!!
	actionLog_->setChecked(false);
	
	MvQMainWindow::MenuType menuType=MvQMainWindow::ViewMenu;
	
	menuItems_[menuType].push_back(new MvQMenuItem(actionFileInfo_));	
	menuItems_[menuType].push_back(new MvQMenuItem(actionLog_));
}

void MvQAbstractMessageExaminer::setupEditMenu()
{
	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 MvQAbstractMessageExaminer::setupSettingsMenu()
{
}

void MvQAbstractMessageExaminer::setupProfilesMenu()
{
	//
	QAction* actionNew = new QAction(this);
        actionNew->setObjectName(QString::fromUtf8("actionProfileNew"));
	actionNew->setText(tr("&New profile"));
	actionNew->setToolTip(tr("Create new key profile"));
	QIcon icon;
	icon.addPixmap(QPixmap(QString::fromUtf8(":/keyDialog/profile_add.svg")), QIcon::Normal, QIcon::Off);
 	actionNew->setIcon(icon);
	
	actionSave_ = new QAction(this);
        actionSave_->setObjectName(QString::fromUtf8("actionProfileSave"));
	actionSave_->setText(tr("&Save profile"));
	actionSave_->setToolTip(tr("Save key profile"));
	QIcon icon1;
	icon1.addPixmap(QPixmap(QString::fromUtf8(":/keyDialog/profile_save.svg")), QIcon::Normal, QIcon::Off);
 	actionSave_->setIcon(icon1);
	actionSave_->setEnabled(false);

	QAction* actionSaveAs = new QAction(this);
        actionSaveAs->setObjectName(QString::fromUtf8("actionProfileSaveAs"));
	actionSaveAs->setText(tr("&Duplicate profile ..."));
	actionSaveAs->setToolTip(tr("Duplicate key profile"));
	QIcon icon2;
	icon2.addPixmap(QPixmap(QString::fromUtf8(":/keyDialog/profile_duplicate.svg")), QIcon::Normal, QIcon::Off);
 	actionSaveAs->setIcon(icon2);

	QAction* actionProfileManager = new QAction(this);
        actionProfileManager->setObjectName(QString::fromUtf8("actionKeyProfileManager"));
	actionProfileManager->setText(tr("&Manage profiles"));
	actionProfileManager->setToolTip(tr("Manage key profiles"));
	QIcon icon3;
	icon3.addPixmap(QPixmap(QString::fromUtf8(":/keyDialog/profile_manage.svg")), QIcon::Normal, QIcon::Off);
 	actionProfileManager->setIcon(icon3);
	actionProfileManager->setToolTip(tr("Key profile manager"));

	/*QAction* actionExport = new QAction(this);
        actionExport->setObjectName(QString::fromUtf8("actionProfileExport"));
	actionExport->setText(tr("&Export"));
	actionExport->setToolTip(tr("Export key profiles"));

	QAction* actionImport = new QAction(this);
        actionImport->setObjectName(QString::fromUtf8("actionProfileImport"));
	actionImport->setText(tr("&Import"));
	actionImport->setToolTip(tr("Import key profiles"));*/

 	
	//Key profile management

	connect(actionNew, SIGNAL(triggered()), 
		this, SLOT(slotCreateNewProfile()));

	connect(actionSave_, SIGNAL(triggered()), 
		this, SLOT(slotSaveCurrentProfile()));

	connect(actionSaveAs, SIGNAL(triggered()), 
		this, SLOT(slotSaveAsCurrentProfile()));

	connect(actionProfileManager, SIGNAL(triggered()), 
		this, SLOT(slotManageKeyProfiles()));

	
	//Combo box
	//We will add items + signal/slots later in "init"!
	QHBoxLayout *hb=new  QHBoxLayout;

	//Combo box for key profile selection
	QLabel *keyLabel = new QLabel(tr("Key profile:"));
	keyCombo_ = new QComboBox;
	keyLabel->setBuddy(keyCombo_);

	hb->addWidget(keyLabel);
	hb->addWidget(keyCombo_);
	QWidget* wh=new QWidget;
	wh->setLayout(hb);

	//MvQMenuItem::MenuTarget

	MvQMainWindow::MenuType menuType=MvQMainWindow::ProfilesMenu;
	
	menuItems_[menuType].push_back(new MvQMenuItem(actionNew));	
	menuItems_[menuType].push_back(new MvQMenuItem(actionSave_));
	menuItems_[menuType].push_back(new MvQMenuItem(actionSaveAs));	
	//menuItems_["profiles"].push_back(new MvQMenuItem(actionExport,MvQMenuItem::MenuTarget));
	//menuItems_["profiles"].push_back(new MvQMenuItem(actionImport,MvQMenuItem::MenuTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(actionProfileManager));
	//menuItems_["profiles"].push_back(new MvQMenuItem(actionKeyManager,MvQMenuItem::MenuTarget));	
	menuItems_[menuType].push_back(new MvQMenuItem(wh));
}

void MvQAbstractMessageExaminer::setupHelpMenu()
{		
    	// 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 ") +  appName_);

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

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


void MvQAbstractMessageExaminer::init(MvMessageMetaData *data,MvQKeyManager *manager)
{	
	data_=data;
	keyManager_=manager;

	data_->registerObserver(this);

	QFileInfo info(QString::fromStdString(data_->fileName()));
	fileSize_=info.size();

	//----------------------------------
	// Initilaize the key profile list
	//---------------------------------

	//Init key combo
   	int currentIndex=-1;
	for (unsigned int i=0; i < keyManager_->data().size();i++) 
	{
		QString str(keyManager_->data().at(i)->name().c_str());
		keyCombo_->addItem(str);
		if(savedKeyProfileName_==str)
		{
			currentIndex=i;
		}
		if(keyManager_->data().at(i)->systemProfile())
		{
			keyCombo_->setItemIcon(i,QPixmap(QString::fromUtf8(":/window/metview_logo")));
		}
		
	}

	//If we do not find a matching a item will select the last one!
	if(currentIndex == -1)
		currentIndex=keyCombo_->count()-1;

	//Set the keyCombo_'s current index to -1 and define the signal-slot for the keyCombo_
	keyCombo_->setCurrentIndex(-1);
	
	connect(keyCombo_, SIGNAL(currentIndexChanged(int)),  
		this,SLOT(slotLoadKeyProfile(int)));

	//Now the currentIndex in keyCombo_ is set to -1, but the currentIndex local variable stores
	//a non-negativ value. So by setting the current index in the keyCombo_ the slot 
	//above will be called and the right key profile will be loaded.
	keyCombo_->setCurrentIndex(currentIndex);

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

	
	messageTree_->setPredefinedKeysOnly(keyManager_->predefinedKeysOnly());


	//Init dump panel
	initDumps();

	//Fileinfo label
	updateFileInfoLabel();

	//Get all keys
	//Init dump panel
	initAllKeys();
}

void MvQAbstractMessageExaminer::setCurrentKeyProfileName(QString name)
{
	if(keyManager_)
	{
		for(unsigned int i=0; i < keyManager_->data().size(); i++)
		{
			QString str(keyManager_->data().at(i)->name().c_str());
			if(str == name)
			{
				keyCombo_->setCurrentIndex(i);
				break;
			}
		}
	}
}

void MvQAbstractMessageExaminer::slotLoadKeyProfile(int index)
{
	//qDebug() << "loadKeyProfile " << index  << " " << keyManager_->data().size();

	saveProfileBeforeAction(false);

	if(index != -1) 
	{
		loadKeyProfile(keyManager_->data().at(index));
		slotUpdateLogOutput();
		//emit keyProfileLoaded(keyManager_->data().at(index));	
	}
}

void MvQAbstractMessageExaminer::loadKeyProfile(MvKeyProfile *prof)
{	
	emit statusMessage(tr("Load new keyprofile ..."));

	messageModel_->keyProfileIsAboutToChange();

	//Create a tmp profile with contents of the current profile
	if(tmpProfile_)
	{
		delete tmpProfile_;
	}
	tmpProfile_= new MvKeyProfile(*prof);

	//Update grib metadata with the new key profile
	loadKeyProfileCore(tmpProfile_);

	//---------------------
	// Update message tree
	//---------------------
	
	messageModel_->setKeyProfile(tmpProfile_);

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

	messageTree_->setCurrentIndex(messageSortModel_->index(0,0));


	if(prof->systemProfile())
	{
		messageTree_->setEditable(false);
	}
	else
	{
		messageTree_->setEditable(true);
	}

	slotSelectMessage(messageTree_->currentIndex());
	
}

void MvQAbstractMessageExaminer::loadKeyProfileCore(MvKeyProfile *prof)
{
	int num;

	if(data_->useMessageSizeForProgressIndicator())
	{
		num=fileSize_;
	}
	else
	{
		num=data_->messageNum();
		if(num == 0)
		{
			num=data_->getEstimatedMessageNum();
		}
	}

	if(num>0)
	{	
		int minDuration=1000.;
		if(fileSize_> 5000000)
		{
			minDuration=0;
		}

	
		QProgressDialog progress("Scan " + messageType_ + " messages ...", QString(), 0, num);
		progress.setWindowModality(Qt::WindowModal);
		progress.setMinimumDuration(minDuration);

		connect(this,SIGNAL(messageScanProgess(int)),
			&progress,SLOT(setValue(int)));
	
		progress.setValue(0);

		//Update grib metadata with the new key profile
		data_->loadKeyProfile(prof);

		//progress.setValue(num);
	}
	else
	{
		data_->loadKeyProfile(prof);
	}

	emit logOutputChanged();
}

void MvQAbstractMessageExaminer::slotSelectMessage(int msgCnt)
{
	QModelIndex srcIndex=messageModel_->index(msgCnt,0);
	messageTree_->setCurrentIndex(messageSortModel_->mapFromSource(srcIndex));
	slotSelectMessage(messageTree_->currentIndex()); 
}

void MvQAbstractMessageExaminer::slotSelectMessage(QModelIndex index)
{	
	int cnt=messageSortModel_->mapToSource(index).row(); 

	string fdump;

	if(currentMessageNo_ == cnt)
	{
		return;
	}

	currentMessageNo_=cnt;

	//Override cursor
	QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));

	//Load dumps
	loadDumps();


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

	//Generate and read grib dumps
	switch(dumpCombo_->currentIndex())
	{
	case 0:
		loadMvDump();
		break;
	case 1:
		loadStdDump();
		break;
	case 2:
		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);
		}
	}*/	

	//Log
	slotUpdateLogOutput();

	//emit messageSelected(currentMessageNo_);

	//Preview plot
	//createPlot();

	//Log
	//updateLogOutput();

	//Restore cursor
	QApplication::restoreOverrideCursor();
}

void MvQAbstractMessageExaminer::slotReloadProfile()
{
	emit statusMessage(tr("Reload key profile ..."));

	//This slot is "called" from MvQKeyProfile model if new key is inserted.
	//It is called between beginResetModel() and endResetModel() calls!!

	//Get the current profile from the model.
	//If everything is fine this must be the tmpProfile_
	MvKeyProfile* prof = messageModel_->keyProfile();

	//Clear the data
	if(prof != 0)
		prof->clearKeyData();	

	//Update grib metadata with the new key profile
	loadKeyProfileCore(prof);

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

	messageTree_->setCurrentIndex(messageSortModel_->index(0,0));
	slotSelectMessage(messageTree_->currentIndex());

	actionSave_->setEnabled(true);
	//keyManager_->saveProfiles();
}

void MvQAbstractMessageExaminer::slotProfileChanged(bool reload)
{
	actionSave_->setEnabled(true);
	if(reload)
	{
		slotReloadProfile();
	}

	//keyManager_->saveProfiles();
}

void MvQAbstractMessageExaminer::slotCreateNewProfile()
{
	bool ok;
     	QString text = QInputDialog::getText(0, tr("New profile"),
                                          tr("New profile name:"), QLineEdit::Normal,
                                          "", &ok);
	if(ok && !text.isEmpty())
        {
	 	keyManager_->addProfile(text.toStdString());		
		keyCombo_->addItem(text);
		keyCombo_->setCurrentIndex(keyCombo_->count()-1);
		actionSave_->setEnabled(false);
	}
}

void MvQAbstractMessageExaminer::slotSaveCurrentProfile()
{
	if(!tmpProfile_)
		return;

	keyManager_->changeProfile(tmpProfile_->name(),tmpProfile_);
	actionSave_->setEnabled(false);
}

void MvQAbstractMessageExaminer::slotSaveAsCurrentProfile()
{
	if(!tmpProfile_)
		return;

	bool ok;
     	QString text = QInputDialog::getText(0, tr("Duplicate profile"),
                                          tr("New profile name:"), QLineEdit::Normal,
                                          "", &ok);
	if(ok && !text.isEmpty())
        { 	
		keyManager_->addProfile(text.toStdString(),tmpProfile_);
		keyCombo_->addItem(text);
		keyCombo_->setCurrentIndex(keyCombo_->count()-1);
		actionSave_->setEnabled(false);
	}


//keyManager_->changeProfile(tmpProfile_->name(),tmpProfile_);
	//actionSave_->setEnabled(false);
}


void MvQAbstractMessageExaminer::messageScanStepChanged(int step)
{
	emit messageScanProgess(step);
}

//-----------------------------------------------------
// Key manager
//-----------------------------------------------------

void MvQAbstractMessageExaminer::slotManageKeyProfiles()
{	
	saveProfileBeforeAction(false);
	
	MvQKeyManager::KeyType type;
	if(messageType_== "GRIB")
	{
		type=MvQKeyManager::GribType;
	}
	else if(messageType_== "BUFR")
	{
		type=MvQKeyManager::BufrType;
	}
	else
	{
		return;
	}

	//Create a tmp copy of the whole manager (no data
	//values, just key descriptions)
	MvQKeyManager *tmpManager=keyManager_->clone();

	MvQKeyDialog profDialog("Metview - " + messageType_ + tr(" Key Profile Manager"),type,tmpManager,keyCombo_->currentIndex(),allKeys_);

	if(profDialog.exec()  == QDialog::Accepted)
	{
		//Save the current profile name
		string currentProfName=keyCombo_->currentText().toStdString(); 
		
		messageModel_->keyProfileIsAboutToChange();
		messageModel_->setKeyProfile(0);

		keyManager_->update(tmpManager);
		keyManager_->saveProfiles();

		disconnect(keyCombo_, SIGNAL(currentIndexChanged(int)),0,0);

		//Clear the profile list
		keyCombo_->clear();

		//resetMessageHeader();

		int i=0;
		int index=-1;
		for (vector<MvKeyProfile*>::const_iterator it=keyManager_->data().begin(); it != keyManager_->data().end(); it++) 
		{
			keyCombo_->addItem(QString((*it)->name().c_str() ));
			if((*it)->name()== currentProfName)
			{
				index=i;
			}
			if(keyManager_->data().at(i)->systemProfile())
			{
				keyCombo_->setItemIcon(i,QPixmap(QString::fromUtf8(":/window/metview_logo")));
			}

			i++;
		}

		keyCombo_->setCurrentIndex(-1);

		connect(keyCombo_, SIGNAL(currentIndexChanged(int)),  
			this,SLOT(slotLoadKeyProfile(int)));

		if(index != -1)
		{
			keyCombo_->setCurrentIndex(index);
		}
		else
		{
			keyCombo_->setCurrentIndex(0);
		}
	}

	delete tmpManager;
}


bool MvQAbstractMessageExaminer::saveProfileBeforeAction(bool offerCancel)
{
	if(actionSave_->isEnabled() == false)
		return true;
	
	QString str=tr("The current key profile as been modified.<br>Do you want to save your changes or discard them?");

 	QMessageBox msgBox;
	msgBox.setWindowTitle(tr("Save changes to current profile"));
	msgBox.setText(str);
	msgBox.setIcon(QMessageBox::Warning);

	if(offerCancel)
	{
 		msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
	}
	else
	{
		msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard);
	}

	msgBox.setDefaultButton(QMessageBox::Save);
	int ret=msgBox.exec();

	switch (ret) 
	{
   	case QMessageBox::Save:
		slotSaveCurrentProfile();				
		break;
   	case QMessageBox::Cancel:
		return false;	
       		break;
   	default:
      	 	break;
	}

	actionSave_->setEnabled(false);

	return true;
}


void MvQAbstractMessageExaminer::slotUpdateLogOutput()
{
	QString buf;

	for(vector<LogItem*>::const_iterator it = LogHandler::instance()->item().begin(); 
	     it != LogHandler::instance()->item().end(); it++)
	{
		LogItem *log=*it;


		if(log->errorStatus()) 
		{
			buf="<b>Status: </b><font color=red>FAILED</font>";
			emit statusMessage(buf);
			break;
		}
		else
		{
			buf="<b>Status: </b><font color=green>OK</font>";
			emit statusMessage(buf);
		}
	}

	logBrowser_->update();
}


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


QString MvQAbstractMessageExaminer::currentKeyProfileName() 
{
	return keyCombo_->currentText();
}
