/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <qstring.h>

#include "utils.h"

struct FormattedValue Utils::getFormattedBytes( double value )
{
	struct FormattedValue fv;
	double amount;

	if( value >= 1073741824 )
	{
		amount = value / 1073741824;
		fv.unitString = "GByte";
	}
	else if( value >= 1048576 )
	{
		amount = value / 1048576;
		fv.unitString = "MByte";
	}
	else if( value >= 1024 )
	{
		amount = value / 1024;
		fv.unitString = "KByte";
	}
	else
	{
		amount = value;
		fv.unitString = "Byte";
	}

	fv.valueString = getNormalizedValueString(amount);
	return fv;
}

struct FormattedValue Utils::getFormattedBits( double value )
{
	struct FormattedValue fv;
	double amount;

	value *= 8;
	if( value >= 1000000000 )
	{
		amount = value / 1000000000;
		fv.unitString = "Gbit";
	}
	else if( value >= 1000000 )
	{
		amount = value / 1000000;
		fv.unitString = "Mbit";
	}
	else if( value >= 1000 )
	{
		amount = value / 1000;
		fv.unitString = "Kbit";
	}
	else
	{
		amount = value;
		fv.unitString = "bit";
	}

	fv.valueString = getNormalizedValueString(amount);
	return fv;
}

struct FormattedValue Utils::getFormattedPackets( double value )
{
	struct FormattedValue fv;
	double amount;
	
	if( value >= 1000000000 )
	{
		amount = value / 1000000000;
		fv.unitString = "e9 pkts";
	}
	else if( value >= 1000000 )
	{
		amount = value / 1000000;
		fv.unitString = "e6 pkts";
	}
	else if( value >= 1000 )
	{
		amount = value / 1000;
		fv.unitString = "e3 pkts";
	}
	else
	{
		amount = value;
		fv.unitString = "pkts";
	}

	fv.valueString = getNormalizedValueString(amount);
	return fv;
}

QString Utils::getNormalizedValueString( double value )
{
	QString s;
	s.sprintf( "%.3f", value );
	s = s.left(5);
	int left;
	for( left=s.length(); left>=1; left-- )
		if( s[left-1] != '0' ) break;
	s = s.left(left);
	if( s[s.length()-1] == '.' )
		s = s.left(s.length()-1);
	return s;
}
