using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Inspectron.Settings;
using Inspectron.Settings.Avalonia.Configuration;
using VisionBuilder.UI.Common.ViewModel.Interfaces.UI;

namespace VisionBuilder.UI.Avalonia.Services;

public class AvaloniaSettingsService : ISettingsService
{
    private readonly InspectronSettings _settings;

    public AvaloniaSettingsService(InspectronSettings settings)
    {
        _settings = settings;
    }

    public async Task ShowSettingsDialogAsync()
    {
        var dialog = new OptionsWindow(new DefaultControlFactory());
        dialog.LoadFromSettings(_settings);
        var parent = GetMainWindow();
        if (parent != null)
        {
            var result = await dialog.ShowDialog<bool>(parent);
            if (result)
                _settings.SaveSettings();
        }
    }

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