using Microsoft.Windows.AppLifecycle;
using MBN_STOCK_WEBVIEW.Playout.Configuration;

namespace MBN_STOCK_WEBVIEW.LegacyParityApp;

public partial class App : Application
{
    private const string MainInstanceKey = "Wickedness.MBNStockWebView.LegacyParity.Main";

    private Window? _window;
    private AppInstance? _mainInstance;

    internal static bool IsDevelopmentLiveLaunch { get; private set; }

    internal static bool IsDevelopmentLiveLaunchRequested { get; private set; }

    internal static string? DevelopmentLiveStartupFailureCode { get; private set; }

    internal static string? DevelopmentLiveStartupFailureMessage { get; private set; }

    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
            {
                Exit();
            }

            return;
        }

        _mainInstance = registeredInstance;
        _mainInstance.Activated += OnMainInstanceActivated;

        // A fresh clone cannot become a full runtime inside the already compiled
        // source-only process. Show only the native two-folder setup window; the
        // reviewed initializer builds the verified runtime for the next F5.
#if SOURCE_ONLY_RUNTIME
        IsDevelopmentLiveLaunchRequested = false;
        IsDevelopmentLiveLaunch = false;
        DevelopmentLiveStartupFailureCode = null;
        DevelopmentLiveStartupFailureMessage = null;
        _window = new FirstRunSetupWindow();
#else
        var launchArguments = DevelopmentLiveLaunchBootstrap.ResolveLaunchArguments(
            args.Arguments,
            Environment.GetCommandLineArgs());
        var developmentLive = DevelopmentLiveLaunchBootstrap.TryApply(launchArguments);
        IsDevelopmentLiveLaunchRequested = developmentLive.IsRequested;
        IsDevelopmentLiveLaunch = developmentLive.IsApplied;
        DevelopmentLiveStartupFailureCode = developmentLive.IsLaunchAllowed
            ? null
            : developmentLive.Code;
        DevelopmentLiveStartupFailureMessage = developmentLive.FailureMessage;
        System.Diagnostics.Debug.WriteLine(
            $"Development Live bootstrap: {developmentLive.Code}");

        _window = new MainWindow();
#endif
        _window.Activate();
    }

    private void OnMainInstanceActivated(object? sender, AppActivationArguments args)
    {
        _window?.DispatcherQueue.TryEnqueue(_window.Activate);
    }
}
