/* Web Polygraph       http://www.web-polygraph.org/
 * (C) 2003-2006 The Measurement Factory
 * Licensed under the Apache License, Version 2.0 */

#include "base/polygraph.h"

#include "xstd/gadgets.h"
#include "base/ILog.h"
#include "base/OLog.h"
#include "base/SslIntvlStat.h"


SslIntvlStat::SslIntvlStat(): theErrXacts(0) {
}

void SslIntvlStat::restart() {
	theDoneXacts.reset();
	theXactLvl.restart();
	theConnLvl.restart();
	theErrXacts = 0;
}

bool SslIntvlStat::active() const {
	return theDoneXacts.active() || theXactLvl.active() ||
		theConnLvl.active() || theErrXacts > 0;
}

bool SslIntvlStat::sane() const {
	return theDoneXacts.sane() && theXactLvl.sane() &&
		theConnLvl.sane() && theErrXacts >= 0;
}

void SslIntvlStat::keepLevel(const SslIntvlStat &s) {
	theXactLvl.keepLevel(s.theXactLvl);
	theConnLvl.keepLevel(s.theConnLvl);
}

double SslIntvlStat::reqRate(Time duration) const {
	return duration > 0 ?
		Ratio(theErrXacts + theDoneXacts.xacts().count(), duration.secd()) : -1;
}

double SslIntvlStat::repRate(Time duration) const {
	return duration > 0 ?
		Ratio(theDoneXacts.xacts().count(), duration.secd()) : -1;
}

OLog &SslIntvlStat::store(OLog &log) const {
	const bool a = active();
	log << a;
	if (a)
		log << theDoneXacts << theXactLvl << theConnLvl << theErrXacts;
	return log;	
}

ILog &SslIntvlStat::load(ILog &log) {
	if (log.getb()) // active?
		log >> theDoneXacts >> theXactLvl >> theConnLvl >> theErrXacts;
	else
		restart();
	return log;
}

void SslIntvlStat::merge(const SslIntvlStat &s) {
	theXactLvl.merge(s.theXactLvl);
	theConnLvl.merge(s.theConnLvl);
	join(s);
}

void SslIntvlStat::concat(const SslIntvlStat &s) {
	theXactLvl.concat(s.theXactLvl);
	theConnLvl.concat(s.theConnLvl);
	join(s);
}

void SslIntvlStat::join(const SslIntvlStat &s) {
	theDoneXacts += s.theDoneXacts;
	theErrXacts += s.theErrXacts;
}

ostream &SslIntvlStat::print(ostream &os, const String &pfx, Time duration) const {
	os << pfx << "req.rate:\t " << reqRate(duration) << endl;
	os << pfx << "rep.rate:\t " << repRate(duration) << endl;

	theDoneXacts.xacts().print(os, pfx + "rep.");
	theDoneXacts.print(os, "hit", "miss", pfx);
	theXactLvl.print(os, pfx + "xact.");
	theConnLvl.print(os, pfx + "conn.");

	os << pfx << "errors.count:\t " << theErrXacts << endl;
	return os;
}


syntax highlighted by Code2HTML, v. 0.9.1