using System;
using System.Reflection;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using Elfisa.Avalonia.ViewModels;
using Elfisa.Core;

namespace Elfisa.Avalonia.Views;

public partial class ShellView : UserControl
{
    private static bool _updateChecked; // один раз за запуск

    public ShellView()
    {
        AvaloniaXamlLoader.Load(this);
        Loaded += OnLoaded;
    }

    private async void OnSettingsClick(object? sender, RoutedEventArgs e)
    {
        var win = new SettingsWindow { DataContext = new SettingsViewModel() };
        var owner = (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.MainWindow;
        if (owner is not null) await win.ShowDialog(owner);
        else win.Show();
    }

    // Проверка обновлений при первом появлении шелла. Тихо игнорируем офлайн/ошибки.
    private async void OnLoaded(object? sender, RoutedEventArgs e)
    {
        if (_updateChecked) return;
        _updateChecked = true;

        try
        {
            var current = Assembly.GetEntryAssembly()?.GetName().Version ?? new Version(0, 0, 0, 0);
            var info = await UpdateService.CheckAsync(current);
            if (info is not { Available: true }) return;

            await Dispatcher.UIThread.InvokeAsync(async () =>
            {
                var win = new UpdateWindow();
                win.DataContext = new UpdateViewModel(info, win.Close);
                var owner = (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.MainWindow;
                if (owner is not null) await win.ShowDialog(owner);
                else win.Show();
            });
        }
        catch { /* обновление не должно мешать работе */ }
    }
}
