namespace InnovEnergy.Lib.Units;

public abstract class Unit
{
    protected Unit(Double value) => Value = value;

    public abstract String Symbol { get; }
    public Double Value { get;  }

    //public override String ToString() => $"{Value} {Symbol}";
    public override String ToString() => ToDisplayString();

    private static readonly IReadOnlyList<String> Prefix = new[] { "y", "z", "a", "f", "p", "n", "ยต", "m", "", "k", "M", "G", "T", "P", "E", "Y" };

    private static Int32 MaxPrefix    { get; } = Prefix.Count - 1;
    private static Int32 DefaultIndex { get; } = Prefix.TakeWhile(e => e != "").Count();
    
    public String ToDisplayString()
    {
        if (Value == 0)
            return $"0 {Symbol}";

        var a = Math.Abs(Value);
        var s = Math.Sign(Value);

        var i = DefaultIndex;

        while (a >= 10000 && i < MaxPrefix)
        {
            a /= 1000;
            i++;
        }
        while (a < 10 && i > 0)
        {
            a *= 1000;
            i--;
        }

        var r = a < 100
            ? Math.Floor(a * 10) / 10
            : Math.Floor(a);

        return $"{r * s} {Prefix[i]}{Symbol}";
    }

    
}