2026-01-10 20:39:17 +01:00
|
|
|
using System.Text.Json;
|
|
|
|
|
using PlanTempus.Application.Features.Localization.Models;
|
|
|
|
|
|
|
|
|
|
namespace PlanTempus.Application.Features.Localization.Services;
|
|
|
|
|
|
|
|
|
|
public class JsonLocalizationService : ILocalizationService
|
|
|
|
|
{
|
|
|
|
|
private readonly string _translationsPath;
|
2026-01-25 17:05:24 +01:00
|
|
|
private readonly Dictionary<string, JsonDocument> _cache = new();
|
2026-01-10 20:39:17 +01:00
|
|
|
|
|
|
|
|
public JsonLocalizationService(IWebHostEnvironment env)
|
|
|
|
|
{
|
|
|
|
|
_translationsPath = Path.Combine(env.ContentRootPath, "Features", "Localization", "Translations");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string CurrentCulture => "da";
|
|
|
|
|
|
|
|
|
|
public string Get(string key, string? culture = null)
|
|
|
|
|
{
|
|
|
|
|
culture ??= CurrentCulture;
|
2026-01-25 17:05:24 +01:00
|
|
|
var doc = GetDocument(culture);
|
2026-01-10 20:39:17 +01:00
|
|
|
|
2026-01-25 17:05:24 +01:00
|
|
|
if (doc == null)
|
2026-01-10 20:39:17 +01:00
|
|
|
return key;
|
|
|
|
|
|
|
|
|
|
var parts = key.Split('.');
|
|
|
|
|
JsonElement current = doc.RootElement;
|
|
|
|
|
|
|
|
|
|
foreach (var part in parts)
|
|
|
|
|
if (!current.TryGetProperty(part, out current))
|
|
|
|
|
return key;
|
|
|
|
|
|
|
|
|
|
return current.GetString() ?? key;
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-25 17:05:24 +01:00
|
|
|
private JsonDocument? GetDocument(string culture)
|
|
|
|
|
{
|
|
|
|
|
if (_cache.TryGetValue(culture, out var cached))
|
|
|
|
|
return cached;
|
|
|
|
|
|
|
|
|
|
var filePath = Path.Combine(_translationsPath, $"{culture}.json");
|
|
|
|
|
|
|
|
|
|
if (!File.Exists(filePath))
|
|
|
|
|
return null;
|
|
|
|
|
|
|
|
|
|
var json = File.ReadAllText(filePath);
|
|
|
|
|
var doc = JsonDocument.Parse(json);
|
|
|
|
|
_cache[culture] = doc;
|
|
|
|
|
|
|
|
|
|
return doc;
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-10 20:39:17 +01:00
|
|
|
public IEnumerable<SupportedCulture> GetSupportedCultures()
|
|
|
|
|
{
|
|
|
|
|
return new List<SupportedCulture>
|
|
|
|
|
{
|
|
|
|
|
new() { Code = "da", Name = "Danish", NativeName = "Dansk" },
|
|
|
|
|
new() { Code = "en", Name = "English", NativeName = "English" }
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|