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

namespace ViKPI.Internal
{
    /// <summary>
    /// Runs actions one at a time, in order, on a background thread. On platforms without threads
    /// (WebGL) actions run inline on the caller's thread.
    /// </summary>
    internal sealed class SerialWorker : IDisposable
    {
        private readonly Queue<Action> _queue = new Queue<Action>();
        private readonly object _lock = new object();
        private readonly Thread _thread;
        private bool _stopping;
        private bool _busy;

        public SerialWorker(string name)
        {
#if UNITY_WEBGL && !UNITY_EDITOR
            _thread = null;
#else
            _thread = new Thread(Run) { Name = name, IsBackground = true, Priority = ThreadPriority.BelowNormal };
            _thread.Start();
#endif
        }

        public int Pending
        {
            get { lock (_lock) return _queue.Count + (_busy ? 1 : 0); }
        }

        public void Post(Action action)
        {
            if (_thread == null)
            {
                Invoke(action);
                return;
            }
            lock (_lock)
            {
                if (_stopping) return;
                _queue.Enqueue(action);
                Monitor.Pulse(_lock);
            }
        }

        /// <summary>Blocks until queued work is done or the timeout passes. Used when the app quits.</summary>
        public bool WaitIdle(int timeoutMs)
        {
            if (_thread == null) return true;
            var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
            lock (_lock)
            {
                while (_queue.Count > 0 || _busy)
                {
                    var left = deadline - DateTime.UtcNow;
                    if (left <= TimeSpan.Zero) return false;
                    Monitor.Wait(_lock, left);
                }
            }
            return true;
        }

        private void Run()
        {
            while (true)
            {
                Action next;
                lock (_lock)
                {
                    while (_queue.Count == 0 && !_stopping) Monitor.Wait(_lock);
                    if (_queue.Count == 0) return;
                    next = _queue.Dequeue();
                    _busy = true;
                }
                Invoke(next);
                lock (_lock)
                {
                    _busy = false;
                    Monitor.PulseAll(_lock);
                }
            }
        }

        private static void Invoke(Action action)
        {
            try { action(); }
            catch (Exception e) { Log.Debug("Background task failed: " + e); }
        }

        public void Dispose()
        {
            lock (_lock)
            {
                _stopping = true;
                Monitor.PulseAll(_lock);
            }
        }
    }
}
