/* Copyright 2009 Palm, Inc.  All rights reserved. */

var PerfLogger = Class.create({
	initialize: function(){
		if(!PerfLogger.isEnabled)
			return;
		this.isEnabled = true;
		this.milestones = $A();
	},
	
	milestone: function(message){
		if (!PerfLogger.isEnabled || !this.isEnabled)
			return;
		this.start = this.start || Date.now();
		var last = this.milestones.last();
		var newest = {
			title: message,
			time: Date.now()
		}
		if (last) {
			newest.elapsed = newest.time - last.time;
			Mojo.Log.info("*** PERF: Time Since " + last.title + " is " + newest.elapsed);
		} else {
			Mojo.Log.info("*** PERF: Starting Perf: " + message)
		}
		this.milestones.push(newest);
		
	},
	
	print: function(){
		if (!PerfLogger.isEnabled || !this.isEnabled)
			return;
		var total = Date.now() - this.start;
		var last = null;
		var output = "***PERF: Summary:\n";
		this.milestones.each(function(m){
			var percent = Math.round(m.elapsed * 10000 / total) / 100;
			if (last) {
				output = output + m.elapsed + "ms / " + percent + "% from " + last.title + " TO " + m.title + "\n";
			}
			last = m;
		});
		Mojo.Log.info(output)
		Mojo.Log.info("*** PERF *** Here is your milestones in JSON");
		Mojo.Log.info(Object.toJSON(this.milestones));
		Mojo.Log.info("*** PERF ***");
	},
	
	purge: function() {
		if(this.milestones)
			this.milestones.clear();
	},
	
	terminate: function() {
		this.isEnabled = false;
	}
});

PerfLogger.isEnabled = false;
