package streamer;
import cc.events.*;
import cc.monitors.AbstractTemporalMonitor;
public class LogMonitor extends AbstractTemporalMonitor {
	private int pairCounter;
	private long pairSum;
	protected int counter = 0;
	protected int efectiveCounter = 0;
	private long sumBytes = 0;
	private long firstTimestamp = 0;
	private long lastTimestamp = 0;
	protected long firstLabel = 0;
	protected long lastLabel = 0;
	
	
	private synchronized void print() {
		if (lastTimestamp != firstTimestamp) {
			float seconds = ((float) (lastTimestamp - firstTimestamp)) / 1000;
			float rate = sumBytes * 8 / seconds / 1000000;
			
			float loss =
				100
					- (((float) efectiveCounter) / (lastLabel - firstLabel))
						* 100;

			/*System.out.println("loss" +  loss );
			System.out.println("loss" +  efectiveCounter );
			System.out.println("loss" +  lastLabel );
			System.out.println("loss" +  firstLabel );
*/
			float delay = (float) (lastTimestamp - firstTimestamp) / counter;
			float fps = counter / seconds;
			float pair;
			if (pairCounter == 0)
				pair = 0;
			else
				pair = ((float) pairSum) / pairCounter;

			System.out.println(
				lastTimestamp
					+ "\t"
					+ rate
					+ " Mbps\t"
					+ loss
					+ " %\t"
					+ pair
					+ " ms\t"
					+ delay
					+ " ms\t"
					+ fps
					+ " fps\t");
		} else {
			//System.out.println("#Log Results Not Representative");
			System.out.print(".");
		}
	}

	protected synchronized void refresh() {
		counter = 0;
		efectiveCounter = 0;
		sumBytes = 0;
		firstTimestamp = lastTimestamp;
		firstLabel = lastLabel;
		pairCounter = 0;
		pairSum = 0;
	}

	public void evaluate() {
		print();
		refresh();
		Client.getInstance().keepAlive();
	}

	public synchronized void update(Event event) {
		counter++;
		sumBytes += event.getSize();
		int label = event.getLabel();
		if (event.getIsPair() && (lastLabel == (label - 1))) {
			pairSum += event.getTimestamp() - lastTimestamp;
			pairCounter++;
		}
		if (label > lastLabel) {
			efectiveCounter++;
			lastLabel = label;
		}
		lastTimestamp = event.getTimestamp();
	}
}