using Microsoft.Windows.AppLifecycle;

namespace MBN_STOCK_WEBVIEW;

/// <summary>
/// Application entry point for the packaged WinUI 3 desktop app.
/// </summary>
public partial class App : Application
{
    private const string MainInstanceKey = "Wickedness.MBNStockWebView.Main";

    private Window? _window;
    private AppInstance? _mainInstance;

    public App()
    {
        InitializeComponent();
    }

    protected override async void OnLaunched(LaunchActivatedEventArgs args)
    {
        var registeredInstance = AppInstance.FindOrRegisterForKey(MainInstanceKey);
        if (!registeredInstance.IsCurrent)
        {
            try
            {
                var activation = AppInstance.GetCurrent().GetActivatedEventArgs();
                if (activation is not null)
                {
                    await registeredInstance.RedirectActivationToAsync(activation);
                }
            }
            finally
            {
                // The secondary process owns no DB, WebView, or playout runtime. End it only
                // after the activation has been handed to the registered primary instance.
                Exit();
            }

            return;
        }

        _mainInstance = registeredInstance;
        _mainInstance.Activated += OnMainInstanceActivated;
        _window = new MainWindow();
        _window.Activate();
    }

    private void OnMainInstanceActivated(object? sender, AppActivationArguments args)
    {
        var window = _window;
        if (window is null)
        {
            return;
        }

        window.DispatcherQueue.TryEnqueue(window.Activate);
    }
}
