using System;
using static System.String;

namespace Quadarax.Foundation.Core.Value.Formatters
{
    /// <summary>
    /// Formats a numeric value based on a format P:Plural:Singular
    /// </summary>
    public class PluralFormatter : ICustomFormatter, IFormatProvider
    {

        public string Format(string? format, object? arg, IFormatProvider? formatProvider)
        {
            if (arg !=null)
            {
                var parts = format == null ? Array.Empty<string>() : format.Split(':'); // ["P", "Plural", "Singular"]

                if (parts[0] == "P") // correct format?
                {
                    // which index position to use
                    int partIndex = (arg.ToString() == "1")?2:1;
                    // pick string (safe guard for array bounds) and format
                    return $"{arg} {(parts.Length > partIndex ? parts[partIndex] : "")}";               
                }
            }
            return String.Format(format ?? string.Empty, arg);
        }

        public object? GetFormat(Type? formatType)
        {
            return formatType == typeof(ICustomFormatter)?this:null;
        }   
    }
}
