
// A numeric value with a physical dimension
var unit = function(value, dimension) {
	return {
		// numeric value
		value: value,
		// string name of the unit, such as "events/second"
		dimension: dimension,
		// human readable string
		toString: function() { return this.value.toFixed(2) + " " + this.dimension; },
		// lower is better
		fitness: function() { return Math.abs(Math.log(Math.abs(this.value)) - Math.log(7)); }
	};
}

// Choose the best representation of some values
// Assumes all values are equal, but with different physical dimensions
var bestUnit = function(us) {
	us = us.slice();
	us.sort( function(lhs, rhs) { return lhs.fitness() - rhs.fitness(); } );
	
	return us[0];
}

otsApp.filter('eventsPerSecond', function() {
	return function(input) {
        if (input === null)
            return "";
		if( typeof input !== "number" || input === 0.0 )
			return "0";
		
		return unit(input, "/sec").toString();
	}
});

otsApp.filter('seconds', function() {
	return function(input) {
        if (input === null)
            return "";
		if( typeof input !== "number" || input === 0.0 )
			return "0";
	    return toDuration(input);
	}
});

var toDuration = function(input)
    {
    return bestUnit(
  				[unit(input, "ms"),
  				 unit(input/1000, "sec"),
  				 unit(input/1000/60, "min")]).toString();
    };

otsApp.filter('bandwidth', function() {
	return function(input) {
        if (input === null)
            return "";
		if( typeof input !== "number" || input === 0.0 )
			return "0";

		return toBandwidth(input);
	}
});

var toBandwidth = function(input)
    {
    return bestUnit(
  				[unit(input, "bps"),
  				 unit(input/1000, "kbps"),
  				 unit(input/1000/1000, "mbps"),
  				 unit(input/1000/1000/1000, "gbps")]).toString();
    };

otsApp.filter('percent', function() {
	return function(input) {
        if (input === null)
            return "";
		if( typeof input !== "number" || input === 0.0 )
			return "0";

		return input*100 + "%";
	}
});
