using System;
using System.Collections.Generic;
using System.Threading;

namespace GeoSus.Client
{
    // Event dispatcher pro Unity main thread
// Unity může přidat SynchronizationContext, nebo polling z Update()
public class EventDispatcher
{
    private readonly Queue<Action> _pendingActions = new Queue<Action>();
    private readonly object _lock = new object();
    private SynchronizationContext? _syncContext;
    
    public EventDispatcher()
    {
        // Pokusíme se zachytit aktuální synchronization context (Unity main thread)
        _syncContext = SynchronizationContext.Current;
    }
    
    // Volat z networking vlákna - naplánuje callback na main thread
    public void Post(Action action)
    {
        if (_syncContext != null)
        {
            _syncContext.Post(_ => action(), null);
        }
        else
        {
            // Fallback - přidáme do fronty pro polling
            lock (_lock)
            {
                _pendingActions.Enqueue(action);
            }
        }
    }
    
    // Volat z Unity Update() pokud není SynchronizationContext
    public void ProcessPendingActions()
    {
        Action[] actions;
        lock (_lock)
        {
            if (_pendingActions.Count == 0) return;
            actions = _pendingActions.ToArray();
            _pendingActions.Clear();
        }
        
        foreach (var action in actions)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"EventDispatcher error: {ex}");
            }
        }
    }
    
    public int PendingCount
    {
        get
        {
            lock (_lock)
            {
                return _pendingActions.Count;
            }
        }
    }
}
}
