using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core;
using Avalonia.Data.Core.Plugins;
using System.Linq;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Elfisa.Avalonia.ViewModels;
using Elfisa.Avalonia.Views;

namespace Elfisa.Avalonia;

public partial class App : Application
{
    /// <summary>Дефолтный шрифт интерфейса (когда «По умолчанию»).</summary>
    public const string DefaultFont = "Segoe UI";

    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    /// <summary>Применяет шрифт ко всему приложению (ресурс наследуется всеми окнами).</summary>
    public static void ApplyFont(string? name)
    {
        var family = string.IsNullOrWhiteSpace(name) ? DefaultFont : name!;
        if (Current is { } app)
            app.Resources["AppFontFamily"] = new FontFamily(family);
    }

    /// <summary>Применяет масштаб интерфейса (размер шрифта/текста) к главному окну.</summary>
    public static void ApplyScale(double scale)
    {
        if (Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime d
            && d.MainWindow is MainWindow mw)
            mw.ApplyScale(scale);
    }

    public override void OnFrameworkInitializationCompleted()
    {
        RequestedThemeVariant = Elfisa.Core.SettingsStore.Current.Theme == "Dark"
            ? global::Avalonia.Styling.ThemeVariant.Dark
            : global::Avalonia.Styling.ThemeVariant.Light;

        ApplyFont(Elfisa.Core.SettingsStore.Current.FontFamily);

        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            desktop.MainWindow = new MainWindow
            {
                DataContext = new RootViewModel(),
            };
        }

        base.OnFrameworkInitializationCompleted();
    }
}