// // LanguageService.cs // // Copyright (c) František Boháček. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Security.Cryptography; using NosSmooth.Data.Abstractions.Language; using Remora.Results; namespace NosSmooth.Data.NOSFiles; /// internal class LanguageService : ILanguageService { private readonly IReadOnlyDictionary>> _translations; private readonly LanguageServiceOptions _options; /// /// Initializes a new instance of the class. /// /// The translations. /// The options. public LanguageService ( IReadOnlyDictionary>> translations, LanguageServiceOptions options ) { CurrentLanguage = options.Language; _translations = translations; _options = options; } /// public Language CurrentLanguage { get; set; } /// public Task> GetTranslationAsync ( TranslationRoot root, string key, Language? language = default, CancellationToken ct = default ) { if (!_translations.ContainsKey(language ?? CurrentLanguage)) { return Task.FromResult ( Result.FromError (new NotFoundError($"The requested language {language ?? CurrentLanguage} is not parsed.")) ); } var translations = _translations[language ?? CurrentLanguage]; if (!translations.ContainsKey(root)) { return Task.FromResult(Result.FromSuccess(key)); } var keyTranslations = translations[root]; if (!keyTranslations.ContainsKey(key)) { return Task.FromResult(Result.FromSuccess(key)); } return Task.FromResult(Result.FromSuccess(keyTranslations[key])); } /// public async Task> GetTranslationAsync ( TranslatableString translatableString, Language? language = default, CancellationToken ct = default ) { var translation = await GetTranslationAsync(translatableString.Root, translatableString.Key, language, ct); if (!translation.IsSuccess) { return translation; } if (_options.FillTranslatableStrings) { translatableString.Fill(translation.Entity); } return translation; } }