using System;
using System.Threading.Tasks;
using Microsoft.UI.Dispatching;

namespace Tornado3_2026Election.Common;

public static class UiDispatcher
{
    private static DispatcherQueue? _dispatcherQueue;

    public static void Initialize(DispatcherQueue? dispatcherQueue)
    {
        _dispatcherQueue ??= dispatcherQueue;
    }

    public static void Enqueue(Action action)
    {
        var dispatcherQueue = _dispatcherQueue;
        if (dispatcherQueue is null || dispatcherQueue.HasThreadAccess)
        {
            action();
            return;
        }

        _ = dispatcherQueue.TryEnqueue(() => action());
    }

    public static Task EnqueueAsync(Action action)
    {
        var dispatcherQueue = _dispatcherQueue;
        if (dispatcherQueue is null || dispatcherQueue.HasThreadAccess)
        {
            action();
            return Task.CompletedTask;
        }

        var completionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        if (!dispatcherQueue.TryEnqueue(() =>
            {
                try
                {
                    action();
                    completionSource.SetResult();
                }
                catch (Exception exception)
                {
                    completionSource.SetException(exception);
                }
            }))
        {
            completionSource.SetResult();
        }

        return completionSource.Task;
    }
}
