/*
* Title:	StatisticsWin.cpp 
* Author:	M.Thomas BEAM Ltd
* Date:		2007-02-13
*
* Contents:	Status Display
*
* Mod Rec:
*
*/

#include <StatisticsWin.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qvgroupbox.h>
#include <BList.h>
#include <BError.h>
#include <TmsD.h>
#include <qmessagebox.h>

const int	REFRESH_MS = 1000;


StatisticsWin::StatisticsWin(QWidget* w,Control& c) : ocontrol(c)  {
	QVGroupBox*	t = new QVGroupBox("Statistics",this,"Statistics");
	QPushButton*	refreshButton;
	
	ostatistics = new QTextEdit(t);
	refreshButton = new QPushButton("Refresh",t);
	refreshButton->setMaximumWidth(200);

	owarningActive = false;
	oticker = new QTimer();
	
	QFont f("courier");
	f.setPointSize(10);
	ostatistics->setFont(f);
	connect(refreshButton,SIGNAL(clicked()),this,SLOT(updateForced()));
	connect(&ocontrol,SIGNAL(newConnection()),this,SLOT(updateForced()));
	connect(oticker,SIGNAL(timeout()),this,SLOT(updateTimed()));
}
	
StatisticsWin::~StatisticsWin() {}

	
void StatisticsWin::updateTimed() {
	if (isVisible())
		getStats();
}

void StatisticsWin::updateForced() {
	owarningActive = false;
	getStats();
}



void StatisticsWin::show() {
	owarningActive = false;
	update();
	oticker->start( REFRESH_MS, FALSE ); 	
	QWidget::show();
}	

void StatisticsWin::hide() {
	oticker->stop(); 	
	QWidget::hide();
}	


void StatisticsWin::getStats() {
	BError			err;
	BIter			i;
	BList<Tms::NameValue>	l;
	BString			name;
	BString			value;
	

	if (err = ocontrol.getStatistics(l)) {
		warningDialog("Reading Statistics",err);
	}
		
	ostatistics->clear();
	for (l.start(i);! l.isEnd(i);l.next(i)) {
		BString	s;
		name = l[i].name.pad(30);
		value = l[i].value;
		s.printf("%s %s\n",name.retStr(),value.retStr());
		ostatistics->append(s.retStr());
	}
}

void	StatisticsWin::warningDialog(BString title, BError err){
	BString	m;
	
	if (owarningActive)
		return;
	owarningActive = true;
	m = BString("<h5>") + title + "</h5><p>" + err.getString() + "</p>";
	QMessageBox::warning(this, "Warning", m.retStr());
}


	
