/* 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 <fstream>

#include "xml/XmlAttr.h"
#include "loganalyzers/LoadStex.h"
#include "loganalyzers/ReportBlob.h"
#include "loganalyzers/BlobDb.h"
#include "loganalyzers/RepOpts.h"
#include "loganalyzers/PhaseInfo.h"
#include "loganalyzers/PhaseTrace.h"
#include "loganalyzers/LoadTraceFig.h"


LoadTraceFig::LoadTraceFig(): theStex1(0), theStex2(0), thePhase(0), theTrace(0) {
}

void LoadTraceFig::stats(const Stex *aStex1, const Stex *aStex2, const PhaseInfo *aPhase) {
	theStex1 = aStex1;
	theStex2 = aStex2;
	Should(theStex1 || theStex2);
	thePhase = aPhase;
	theTrace = &thePhase->trace();
	Assert(theTrace);
}

void LoadTraceFig::setCtrlOptions() {
	theLabelY1 = "rate, #/sec";
	theLabelY2 = "bandwidth, Mbits/sec";
	ReportTraceFigure::setCtrlOptions();
}

int LoadTraceFig::createCtrlFile() {
	if (ReportTraceFigure::createCtrlFile() < 0)
		return -1;

	if (theStex1 || theStex2)
		*theCtrlFile << "plot \\" << endl;

	if (theStex1) {
		*theCtrlFile << "\t '-' using 1:2 axis x1y1 title '" <<
			theStex1->name() << " rate' with lines ls 3, \\" << endl;
		*theCtrlFile << "\t '-' using 1:3 axis x1y2 title '" <<
			theStex1->name() << " bwidth (right y-axis)' with lines ls 4";
	}

	if (theStex1 && theStex2)
		*theCtrlFile << ", \\" << endl;

	if (theStex2) {
		*theCtrlFile << "\t '-' using 1:2 axis x1y1 title '" <<
			theStex2->name() << " rate' with lines ls 1, \\" << endl;
		*theCtrlFile << "\t '-' using 1:3 axis x1y2 title '" <<
			theStex2->name() << " bwidth (right y-axis)' with lines ls 2";
	}
	*theCtrlFile << endl;

	int pointCount = 0;

	if (theStex1) {
		pointCount += dumpDataLines(theStex1);
		*theCtrlFile << 'e' << endl;
		dumpDataLines(theStex1);
	}

	if (theStex1 && theStex2)
		*theCtrlFile << 'e' << endl;

	if (theStex2) {
		pointCount += dumpDataLines(theStex2);
		*theCtrlFile << 'e' << endl;
		dumpDataLines(theStex2);
	}

	return pointCount;
}

int LoadTraceFig::dumpDataLines(const LoadStex *stex) {
	int pointCount = 0;
	for (int i = 0; i < theTrace->count(); ++i)
		pointCount += dumpDataLine(stex, theTrace->winPos(i), theTrace->winStats(i));

	return pointCount;
}

int LoadTraceFig::dumpDataLine(const LoadStex *stex, Time stamp, const StatIntvlRec &r) {
	if (true) {
		const double rate = stex->rate(r);
		const double bwidth = stex->bwidth(r);
		dumpTime(stamp);
		*theCtrlFile << ' ' << rate << ' ' << (bwidth*8/1024/1024) << endl;
		return 1;
	}
	return 0;	
}


syntax highlighted by Code2HTML, v. 0.9.1