You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Common/Common/Globalization/GlobalizationService.cs

106 lines
2.4 KiB

2 years ago
using System.Globalization;
using Connected;
using Connected.Data;
using Connected.Globalization;
using Connected.Globalization.Languages;
using Connected.Security.Identity;
using Connected.ServiceModel;
namespace Common.Globalization;
internal class GlobalizationService : IGlobalizationService
{
private ILanguage _language;
private CultureInfo _culture;
public GlobalizationService(IIdentityService identityService, ILanguageService languageService)
{
IdentityService = identityService;
LanguageService = languageService;
}
private IIdentityService IdentityService { get; }
private ILanguageService LanguageService { get; }
public TimeZoneInfo TimeZone
{
get
{
if (!IdentityService.IsAuthenticated || IdentityService.CurrentUser is null)
return TimeZoneInfo.Utc;
else
{
try
{
if (TimeZoneInfo.FindSystemTimeZoneById(IdentityService.CurrentUser.TimeZone) is not TimeZoneInfo timezone)
return TimeZoneInfo.Utc;
else
return timezone;
}
catch
{
return TimeZoneInfo.Utc;
}
}
}
}
public DateTimeOffset Now => FromUtc(DateTimeOffset.UtcNow);
public async Task<ILanguage?> GetCurrentLanguage()
{
if (_language is null)
{
if (IdentityService.CurrentUser is not null && IdentityService.CurrentUser.Language > 0)
_language = await LanguageService.Select(new PrimaryKeyArgs<int>() { Id = IdentityService.CurrentUser.Language });
if (_language is not null && _language.Status == Status.Disabled)
_language = null;
}
return _language;
}
public async Task<CultureInfo> GetCurrentCulture()
{
if (_culture is null)
{
if (await GetCurrentLanguage() is not ILanguage language)
_culture = Thread.CurrentThread.CurrentUICulture;
else
{
try
{
if (CultureInfo.GetCultureInfo(language.Lcid) is not CultureInfo culture)
_culture = Thread.CurrentThread.CurrentUICulture;
}
catch
{
_culture = Thread.CurrentThread.CurrentUICulture;
}
}
}
return _culture;
}
public DateTime FromUtc(DateTime value)
{
return DateExtensions.FromUtc(value, TimeZone);
}
public DateTimeOffset FromUtc(DateTimeOffset value)
{
return DateExtensions.FromUtc(value, TimeZone);
}
public DateTime ToUtc(DateTime value)
{
return DateExtensions.ToUtc(value, TimeZone);
}
public DateTimeOffset ToUtc(DateTimeOffset value)
{
return DateExtensions.ToUtc(value, TimeZone);
}
}