using System;
using System.Globalization;

namespace GravCoin;

public static class NumberFormatter
{
	private static readonly string[] Suffixes =
	{
		"", "k", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc"
	};

	public static string ToFormattedString( this long value ) => ((double)value).ToFormattedString();
	public static string ToFormattedString( this float value ) => ((double)value).ToFormattedString();

	public static string ToFormattedString( this double value )
	{
		if ( double.IsNaN( value ) || double.IsInfinity( value ) )
			return "0";

		double scaled = value;
		double abs = Math.Abs( scaled );
		int suffixIndex = 0;

		while ( abs >= 1000.0 && suffixIndex < Suffixes.Length - 1 )
		{
			scaled /= 1000.0;
			abs /= 1000.0;
			suffixIndex++;
		}

		int decimals = suffixIndex == 0 ? 2 : 2;
		if ( suffixIndex == 0 && abs > 0 && abs < 0.1 ) decimals = 4;

		string format = suffixIndex == 0 ? $"F{decimals}" : "F2";
		string number = scaled.ToString( format, CultureInfo.InvariantCulture );
		
		if ( number.Contains( "." ) )
		{
			number = number.TrimEnd( '0' ).TrimEnd( '.' );
		}

		return number + Suffixes[suffixIndex];
	}
}
