using System.Diagnostics;
using System.Threading;
using Windows.UI.ViewManagement;

namespace MBN_STOCK_WEBVIEW.LegacyParityApp;

public sealed partial class MainWindow
{
    private static readonly TimeSpan StartupIntroMinimumVisibleDuration =
        TimeSpan.FromMilliseconds(2050);
    private static readonly TimeSpan StartupIntroExitDuration =
        TimeSpan.FromMilliseconds(180);

    private readonly Stopwatch _startupIntroStopwatch = new();
    private bool _startupIntroAnimationsEnabled = true;
    private int _startupIntroDismissStarted;

    private void StartStartupIntro()
    {
        _startupIntroStopwatch.Restart();
        try
        {
            _startupIntroAnimationsEnabled = new UISettings().AnimationsEnabled;
        }
        catch
        {
            // If Windows cannot provide the preference, retain the short default
            // animation rather than preventing the application from starting.
            _startupIntroAnimationsEnabled = true;
        }

        if (_startupIntroAnimationsEnabled)
        {
            StartupIntroEnterStoryboard.Begin();
        }
    }

    private void BeginDismissStartupIntro()
    {
        if (Interlocked.CompareExchange(ref _startupIntroDismissStarted, 1, 0) != 0)
        {
            return;
        }

        _ = DismissStartupIntroAsync();
    }

    private async Task DismissStartupIntroAsync()
    {
        try
        {
            var remainingDuration =
                StartupIntroMinimumVisibleDuration - _startupIntroStopwatch.Elapsed;
            if (remainingDuration > TimeSpan.Zero)
            {
                await Task.Delay(
                    remainingDuration,
                    _lifetimeCancellation.Token);
            }

            if (_closing || _lifetimeCancellation.IsCancellationRequested)
            {
                return;
            }

            if (!_startupIntroAnimationsEnabled)
            {
                CompleteStartupIntroDismissal();
                return;
            }

            StartupIntroExitStoryboard.Begin();
            await Task.Delay(
                StartupIntroExitDuration,
                _lifetimeCancellation.Token);
            if (!_closing)
            {
                CompleteStartupIntroDismissal();
            }
        }
        catch (OperationCanceledException)
            when (_lifetimeCancellation.IsCancellationRequested)
        {
        }
        catch
        {
            // A visual transition must never keep the operator from the ready or
            // error surface. Complete synchronously if the animation cannot run.
            if (!_closing)
            {
                CompleteStartupIntroDismissal();
            }
        }
    }

    private void CompleteStartupIntroDismissal()
    {
        LoadingOverlay.Visibility = Visibility.Collapsed;
        LoadingOverlay.IsHitTestVisible = false;
        Browser.IsHitTestVisible = true;
    }
}
