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

namespace Elfisa.Avalonia.Views;

public partial class SettingsWindow : Window
{
    public SettingsWindow() => AvaloniaXamlLoader.Load(this);

    private async void OnCheckUpdate(object? sender, RoutedEventArgs e)
    {
        var status = this.FindControl<TextBlock>("UpdateStatus");
        var current = Assembly.GetEntryAssembly()?.GetName().Version ?? new Version(0, 0, 0, 0);
        if (status is not null) status.Text = "Проверяем…";
        var info = await UpdateService.CheckAsync(current);
        if (info is null)
        {
            if (status is not null) status.Text = "Не удалось проверить (нет сети).";
            return;
        }
        if (!info.Available)
        {
            if (status is not null) status.Text = $"У вас последняя версия ({info.CurrentVersion}).";
            return;
        }
        if (status is not null) status.Text = $"Доступна {info.LatestVersion} — открываю…";
        var win = new UpdateWindow();
        win.DataContext = new UpdateViewModel(info, win.Close);
        await win.ShowDialog(this);
    }

    private void OnSave(object? sender, RoutedEventArgs e)
    {
        if (DataContext is SettingsViewModel vm)
        {
            SettingsStore.Current.ApiBaseUrl = string.IsNullOrWhiteSpace(vm.ApiBaseUrl) ? null : vm.ApiBaseUrl.Trim().TrimEnd('/');
            SettingsStore.Current.Theme = vm.ThemeIndex == 1 ? "Dark" : "Light";
            var font = vm.SelectedFont == SettingsViewModel.DefaultFontLabel ? null : vm.SelectedFont;
            SettingsStore.Current.FontFamily = font;
            SettingsStore.Current.UiScale = vm.SelectedScale;
            SettingsStore.Current.DefaultLocationId = vm.SelectedLocation?.BuyerLocationId;
            SettingsStore.Save();

            if (Application.Current is { } app)
                app.RequestedThemeVariant = vm.ThemeIndex == 1 ? ThemeVariant.Dark : ThemeVariant.Light;
            App.ApplyFont(font);            // шрифт — сразу ко всем окнам
            App.ApplyScale(vm.SelectedScale); // масштаб — к главному окну
        }
        Close();
    }

    private void OnCancel(object? sender, RoutedEventArgs e) => Close();
}
