using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.сеть;
using Mlaumcherb.Client.Avalonia.сеть.Update;
using Mlaumcherb.Client.Avalonia.холопы;

namespace Mlaumcherb.Client.Avalonia.зримое;

public class LauncherApp : Application
{
    public static LauncherLogger Logger = new();
    public static Config Config = null!;
    public static InstalledVersionCatalog InstalledVersionCatalog = null!;
    
    public override void Initialize()
    {
        Logger.LogInfo(nameof(LauncherApp), "приложение запущено");
        Config = Config.LoadFromFile();
        Logger.DebugLogEnabled = Config.debug;
        AvaloniaXamlLoader.Load(this);

        Update();
        
        // some file required by forge installer
        if (!File.Exists("launcher_profiles.json"))
        {
            File.WriteAllText("launcher_profiles.json", "{}");
        }

        InstalledVersionCatalog = InstalledVersionCatalog.Load();
    }

    private async void Update()
    {
        try
        {
            Logger.LogInfo(nameof(LauncherApp), "checking for updates...");
            var upd = new UpdateHelper(Config.gitea);
            upd.DeleteBackupFiles();
            if (await upd.IsUpdateAvailable())
            {
                Logger.LogInfo(nameof(LauncherApp), "downloading update...");
                await upd.UpdateSelf();
                Logger.LogInfo(nameof(LauncherApp), "restarting...");
                upd.RestartSelf();
            }
        }
        catch (Exception e)
        {
            ErrorHelper.ShowMessageBox(nameof(LauncherApp), e);
        }
    }

    public override void OnFrameworkInitializationCompleted()
    {
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            desktop.MainWindow = new MainWindow();
        }

        base.OnFrameworkInitializationCompleted();
    }
}