using System.Globalization;
using Microsoft.JSInterop;
namespace EnvelopeGenerator.ReceiverUI.Services;
///
/// Service for managing application culture/localization.
///
public class CultureService
{
private readonly IJSRuntime _jsRuntime;
private const string CULTURE_KEY = "AppCulture";
public CultureService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
///
/// Gets the list of supported cultures.
///
public static CultureInfo[] SupportedCultures { get; } = new[]
{
new CultureInfo("de-DE"),
new CultureInfo("en-US"),
new CultureInfo("fr-FR")
};
///
/// Sets the application culture and stores it in localStorage.
///
public async Task SetCultureAsync(string culture)
{
if (!SupportedCultures.Any(c => c.Name == culture))
throw new ArgumentException($"Culture '{culture}' is not supported.", nameof(culture));
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", CULTURE_KEY, culture);
}
///
/// Gets the stored culture from localStorage.
///
public async Task GetCultureAsync()
{
try
{
return await _jsRuntime.InvokeAsync("localStorage.getItem", CULTURE_KEY);
}
catch
{
return null;
}
}
///
/// Initializes the culture from localStorage or browser settings.
///
public async Task InitializeCultureAsync()
{
var storedCulture = await GetCultureAsync();
if (!string.IsNullOrEmpty(storedCulture) &&
SupportedCultures.Any(c => c.Name == storedCulture))
{
return new CultureInfo(storedCulture);
}
// Fallback to browser culture or default
var browserCulture = CultureInfo.CurrentCulture.Name;
var matchedCulture = SupportedCultures.FirstOrDefault(c => c.Name == browserCulture);
return matchedCulture ?? SupportedCultures[0]; // Default to German
}
}