//
//  DatabaseLanguageService.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.Runtime.InteropServices.ComTypes;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using NosSmooth.Data.Abstractions.Language;
using Remora.Results;
namespace NosSmooth.Data.Database;
/// 
public class DatabaseLanguageService : ILanguageService
{
    private readonly IDbContextFactory _dbContextFactory;
    private readonly LanguageServiceOptions _options;
    /// 
    /// Initializes a new instance of the  class.
    /// 
    /// The database context factory.
    /// The options.
    public DatabaseLanguageService
    (
        IDbContextFactory dbContextFactory,
        IOptions options
    )
    {
        CurrentLanguage = options.Value.Language;
        _dbContextFactory = dbContextFactory;
        _options = options.Value;
    }
    /// 
    public Language CurrentLanguage { get; set; }
    /// 
    public async Task> GetTranslationAsync(TranslationRoot root, string key, Language? language = default, CancellationToken ct = default)
    {
        try
        {
            language ??= CurrentLanguage;
            await using var context = await _dbContextFactory.CreateDbContextAsync(ct);
            var translation = await context.Translations.AsNoTracking().FirstOrDefaultAsync
                (x => x.Root == root && x.Key == key && x.Language == language, ct);
            if (translation is null)
            {
                return new NotFoundError($"Could not find translation for {root} {key}");
            }
            return translation.Translated;
        }
        catch (Exception e)
        {
            return e;
        }
    }
    /// 
    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;
    }
}