using Erp.Languages.Entities; using Microsoft.Extensions.Localization; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Volo.Abp.Caching; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; using Volo.Abp.Localization; using Volo.Abp.Threading; namespace Erp.Languages.Localization; public class DatabaseResourceLocalizer : IDatabaseResourceLocalizer, ISingletonDependency { private readonly IRepository languageTextRepository; private readonly IDistributedCache cache; public DatabaseResourceLocalizer( IRepository languageTextRepository, IDistributedCache cache) { this.languageTextRepository = languageTextRepository; this.cache = cache; } public LocalizedString GetOrNull(LocalizationResourceBase resource, string cultureName, string name) { var item = GetCacheItem(resource, cultureName); var value = item.Dictionary?.GetOrDefault(name); if (item == null || value == null) { return null; } return new LocalizedString(name, value); } protected LanguageTextCacheItem GetCacheItem(LocalizationResourceBase resource, string cultureName) { // culture, resource, key var key = LanguageTextCacheItem.CalculateCacheKey(resource.ResourceName, cultureName); return cache.GetOrAdd(key, () => CreateCacheItem(resource, cultureName)); } public void Fill(LocalizationResourceBase resource, string cultureName, Dictionary dictionary) { var item = GetCacheItem(resource, cultureName); foreach (var kvp in item.Dictionary) { dictionary[kvp.Key] = new LocalizedString(kvp.Key, kvp.Value); } } protected virtual LanguageTextCacheItem CreateCacheItem(LocalizationResourceBase resource, string cultureName) { //TODO VT'den textleri alip cache'e dolduran kismi yazalim //TODO:SÖ var task = languageTextRepository.GetListAsync(a => a.ResourceName == resource.ResourceName && a.CultureName == cultureName); var texts = AsyncHelper.RunSync(() => task); return new LanguageTextCacheItem { Dictionary = texts.ToDictionary(a => a.Key, a => a.Value) }; } public async Task FillAsync(LocalizationResourceBase resource, string cultureName, Dictionary dictionary) { var key = LanguageTextCacheItem.CalculateCacheKey(resource.ResourceName, cultureName); var item = await cache.GetOrAddAsync(key, () => CreateCacheItemAsync(resource, cultureName)); foreach (var kvp in item.Dictionary) { dictionary[kvp.Key] = new LocalizedString(kvp.Key, kvp.Value); } } protected virtual async Task CreateCacheItemAsync(LocalizationResourceBase resource, string cultureName) { var texts = await languageTextRepository.GetListAsync(a => a.ResourceName == resource.ResourceName && a.CultureName == cultureName); return new LanguageTextCacheItem { Dictionary = texts.ToDictionary(a => a.Key, a => a.Value) }; } }