51 lines
1.4 KiB
C#
51 lines
1.4 KiB
C#
using System.Globalization;
|
|
using System.Net.Http.Json;
|
|
|
|
namespace WebClientTpos.Client.Localization;
|
|
|
|
public class LocalizationCache
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private Dictionary<string, string> _strings = new();
|
|
private bool _isLoaded;
|
|
|
|
public LocalizationCache(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient;
|
|
}
|
|
|
|
public string? GetString(string key)
|
|
{
|
|
if (_strings.TryGetValue(key, out var value))
|
|
{
|
|
return value;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public async Task LoadAsync(CultureInfo culture)
|
|
{
|
|
if (_isLoaded) return; // Or check if culture changed
|
|
|
|
try
|
|
{
|
|
var cultureName = culture.Name;
|
|
// Map generic "vi" to "vi-VN" if needed, but for now we trust the culture name matches file
|
|
// Fallback for simple "vi" -> "vi-VN"
|
|
if (cultureName == "vi") cultureName = "vi-VN";
|
|
if (cultureName == "en") cultureName = "en-US";
|
|
|
|
var loaded = await _httpClient.GetFromJsonAsync<Dictionary<string, string>>($"/locales/{cultureName}.json?v={DateTime.Now.Ticks}");
|
|
if (loaded != null)
|
|
{
|
|
_strings = loaded;
|
|
_isLoaded = true;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Error loading localization for {culture.Name}: {ex.Message}");
|
|
}
|
|
}
|
|
}
|