using System.Collections.Frozen;
using System.Globalization;
using System.Reflection;
using System.Text.Json;
namespace Khaemhat.Application.Localization;
///
/// The texts of the interface (SPEC §1.9, §10.8): keys such as Shell.Menu.Home resolved from
/// Resources/<culture>/*.json. Components never contain literal texts; they ask this service.
///
public interface ITexts
{
/// The culture of the texts and of number and date formats.
CultureInfo Culture { get; }
/// The text of a key; a missing key gives [key], visible in the page and caught by the tests.
/// The key, Area.Entity.Text.
/// The text.
string this[string key] { get; }
/// The text of a key with placeholders filled in the culture.
/// The key.
/// The values for {0}, {1}...
/// The text.
string Format(string key, params object?[] args);
/// Whether a key exists.
/// The key.
/// when it has a text.
bool Contains(string key);
/// Every key, for the tests and the documentation.
IReadOnlyCollection Keys { get; }
}
///
/// Reads the texts from JSON files. Nested objects become dotted keys: {"Shell": {"Menu": {"Home": "Home"}}}
/// gives Shell.Menu.Home; the property _ gives a text to an object that also has children. The file
/// name is not part of the key; two files defining the same key are an error.
///
public sealed class JsonTextProvider : ITexts
{
/// The prefix of the embedded resources holding the texts: texts/it-IT/Shell.json.
public const string ResourcePrefix = "texts/";
private readonly FrozenDictionary _texts;
/// Creates the provider from JSON documents.
/// The culture.
/// The documents, by name (used in error messages).
public JsonTextProvider(CultureInfo culture, IEnumerable> documents)
{
ArgumentNullException.ThrowIfNull(culture);
ArgumentNullException.ThrowIfNull(documents);
Culture = culture;
var texts = new Dictionary(StringComparer.Ordinal);
foreach (var (name, json) in documents)
{
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
if (document.RootElement.ValueKind != JsonValueKind.Object)
{
throw new InvalidDataException($"The texts file {name} must contain an object.");
}
Flatten(document.RootElement, string.Empty, name, texts);
}
_texts = texts.ToFrozenDictionary(StringComparer.Ordinal);
}
///
public CultureInfo Culture { get; }
///
public IReadOnlyCollection Keys => _texts.Keys;
///
public string this[string key] => key is not null && _texts.TryGetValue(key, out var text) ? text : "[" + key + "]";
/// Loads the texts of a culture from the embedded resources of an assembly ().
/// The assembly, usually the web project.
/// The culture, for example it-IT.
/// The provider.
public static JsonTextProvider FromAssembly(Assembly assembly, CultureInfo culture)
{
ArgumentNullException.ThrowIfNull(assembly);
ArgumentNullException.ThrowIfNull(culture);
var prefix = ResourcePrefix + culture.Name + "/";
var documents = new List>();
foreach (var resource in assembly.GetManifestResourceNames().Order(StringComparer.Ordinal))
{
var name = resource.Replace('\\', '/');
if (!name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || !name.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
continue;
}
using var stream = assembly.GetManifestResourceStream(resource)!;
using var reader = new StreamReader(stream);
documents.Add(new(name, reader.ReadToEnd()));
}
if (documents.Count == 0)
{
throw new InvalidOperationException($"No texts for {culture.Name} in {assembly.GetName().Name}.");
}
return new JsonTextProvider(culture, documents);
}
///
public string Format(string key, params object?[] args) => string.Format(Culture, this[key], args);
///
public bool Contains(string key) => key is not null && _texts.ContainsKey(key);
private static void Flatten(JsonElement element, string prefix, string file, Dictionary texts)
{
foreach (var property in element.EnumerateObject())
{
// "_" gives a text to the object itself: {"Menu": {"Parties": {"_": "Anagrafiche", "Customers": "Clienti"}}}.
var key = property.Name == "_" && prefix.Length > 0 ? prefix : prefix.Length == 0 ? property.Name : prefix + "." + property.Name;
switch (property.Value.ValueKind)
{
case JsonValueKind.Object:
Flatten(property.Value, key, file, texts);
break;
case JsonValueKind.String:
if (!texts.TryAdd(key, property.Value.GetString()!))
{
throw new InvalidDataException($"The text {key} is defined twice ({file}).");
}
break;
default:
throw new InvalidDataException($"The text {key} in {file} must be a string or an object.");
}
}
}
}
/// Number, money and date formats of the interface, in the culture of (SPEC §10.8).
public static class TextFormats
{
/// An amount in euro: € 1.234,50.
/// The texts.
/// The amount.
/// The text.
public static string Money(this ITexts texts, decimal amount)
{
ArgumentNullException.ThrowIfNull(texts);
return "€ " + amount.ToString("#,##0.00", texts.Culture);
}
/// A number with a fixed count of decimals: 1.234,5.
/// The texts.
/// The value.
/// The decimals.
/// The text.
public static string Number(this ITexts texts, decimal value, int decimals = 0)
{
ArgumentNullException.ThrowIfNull(texts);
return value.ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), texts.Culture);
}
/// A date: 13/10/2026.
/// The texts.
/// The date.
/// The text.
public static string Date(this ITexts texts, DateOnly date)
{
ArgumentNullException.ThrowIfNull(texts);
return date.ToString("dd/MM/yyyy", texts.Culture);
}
/// A date and time in the given time zone: 13/10/2026 14:05.
/// The texts.
/// The moment, in UTC.
/// The time zone of the user.
/// The text.
public static string DateTime(this ITexts texts, DateTime utc, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(texts);
ArgumentNullException.ThrowIfNull(zone);
var local = TimeZoneInfo.ConvertTimeFromUtc(System.DateTime.SpecifyKind(utc, DateTimeKind.Utc), zone);
return local.ToString("dd/MM/yyyy HH:mm", texts.Culture);
}
}