using VisionBuilder.UI.Common.ViewModel;
using VisionBuilder.UI.Common.ViewModel.Interfaces.UI;
using VisionBuilder.UI.Avalonia.Views;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;

namespace VisionBuilder.UI.Avalonia.Services;

public class AvaloniaRecipeSelectionDialogService : IRecipeSelectionDialogService
{
    private readonly IRecipeCreationTool _recipeCreationTool;

    public AvaloniaRecipeSelectionDialogService(IRecipeCreationTool recipeCreationTool)
    {
        _recipeCreationTool = recipeCreationTool;
    }

    public async Task<bool> SelectRecipeAsync(RecipeSelectionVM recipeSelectionVm)
    {
        var tcs = new TaskCompletionSource<bool>();
        var dialog = new RecipeSelectionDialog(recipeSelectionVm, _recipeCreationTool, tcs);
        var parent = GetMainWindow();
        if (parent != null)
        {
            await dialog.ShowDialog(parent);
            return tcs.Task.IsCompleted && tcs.Task.Result;
        }
        return false;
    }

    private static Window? GetMainWindow()
    {
        if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            return desktop.MainWindow;
        return null;
    }
}
