using Apewer;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Apewer.Internals
{

    internal sealed class LogProvider
    {

        private static bool _running = false;
        private static Thread _thread = null;
        private static Queue<LogItem> _queue = new Queue<LogItem>();

        private static void Listener()
        {
            while (_running)
            {
                var item = (LogItem)null;
                lock (_queue)
                {
                    if (_queue.Count > 0) item = _queue.Dequeue();
                    else
                    {
                        _running = false;
                        break;
                    }
                }

                if (item == null) continue;
                if (item.Logger == null) continue;
                try
                {
                    // item.Logger.Raise(item);
                }
                catch { }
            }
        }

        public static void Queue(LogItem argItem)
        {
            if (argItem == null) return;
            lock (_queue)
            {
                _queue.Enqueue(argItem);
                if (_thread == null)
                {
                    _thread = new Thread(Listener);
                    _thread.IsBackground = false;
                }
                if (!_running)
                {
                    _running = true;
                    _thread.Start();
                }
            }
        }

    }

}