|
| 1 | +using System.Text.Json; |
| 2 | +using System.Text.Json.Serialization; |
| 3 | + |
| 4 | +namespace PopGuard; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// A piece of UI text given either as a plain string (common to every language) or as a |
| 8 | +/// language-keyed object, e.g. <c>{ "ja": "2時間", "en": "2 hours" }</c>. |
| 9 | +/// </summary> |
| 10 | +[JsonConverter(typeof(LocalizedTextConverter))] |
| 11 | +internal sealed class LocalizedText |
| 12 | +{ |
| 13 | + // Per-language text, keyed by two-letter language code (case-insensitive). Null when a common |
| 14 | + // string was given instead. |
| 15 | + private readonly Dictionary<string, string>? _byLang; |
| 16 | + private readonly string? _common; |
| 17 | + |
| 18 | + public LocalizedText(string common) => _common = common; |
| 19 | + |
| 20 | + public LocalizedText(Dictionary<string, string> byLang) => _byLang = byLang; |
| 21 | + |
| 22 | + /// <summary>Build a Japanese/English pair (used for the sample config).</summary> |
| 23 | + public static LocalizedText Of(string ja, string en) => |
| 24 | + new(new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { ["ja"] = ja, ["en"] = en }); |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Resolve the text for the current display language. Returns null when nothing applies, |
| 28 | + /// so the caller can fall back (e.g. auto-generate from the minutes). |
| 29 | + /// A language-keyed object only yields text for the language actually present: if just one |
| 30 | + /// language was given, the others get null (and auto-generate) rather than borrowing it. |
| 31 | + /// A plain string is common to every language. |
| 32 | + /// </summary> |
| 33 | + public string? Resolve(bool japanese) |
| 34 | + { |
| 35 | + if (_byLang is { Count: > 0 }) |
| 36 | + { |
| 37 | + return _byLang.TryGetValue(japanese ? "ja" : "en", out string? v) && !string.IsNullOrWhiteSpace(v) |
| 38 | + ? v.Trim() |
| 39 | + : null; |
| 40 | + } |
| 41 | + return string.IsNullOrWhiteSpace(_common) ? null : _common!.Trim(); |
| 42 | + } |
| 43 | + |
| 44 | + /// <summary>Serialize back (only needed because the sample config is written out).</summary> |
| 45 | + internal void WriteTo(Utf8JsonWriter writer) |
| 46 | + { |
| 47 | + if (_byLang is { Count: > 0 }) |
| 48 | + { |
| 49 | + writer.WriteStartObject(); |
| 50 | + foreach (KeyValuePair<string, string> kv in _byLang) |
| 51 | + { |
| 52 | + writer.WriteString(kv.Key, kv.Value); |
| 53 | + } |
| 54 | + writer.WriteEndObject(); |
| 55 | + } |
| 56 | + else |
| 57 | + { |
| 58 | + writer.WriteStringValue(_common ?? string.Empty); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments