using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Villain.Threading;

namespace Villain.Networking.Packets
{
	public class PacketWorker : QueueWorker
	{
		private readonly new ConcurrentQueue<Action> _queue = new ConcurrentQueue<Action>();
		private readonly Int32 _sleep = 1;

		private bool isRunning = false;

		public PacketWorker() : this(false)
		{

		}

		public PacketWorker(bool start = false) : base()
		{
			if (start)
			{
				Start();
			}
		}

		public void Enqueue(Action callback)
		{
			_queue.Enqueue(callback);
		}

		public override void Start()
		{
			isRunning = true;

			base.Start();
		}

		public void Stop()
		{
			isRunning = false;
		}

		// TODO: Remove this and use a class instead
		public void HandleCallback(object callback)
		{
			((Action)callback)();
		}

		protected override void Work()
		{
			while (isRunning)
			{
				Action callback;

				while (_queue.TryDequeue(out callback))
				{
					// TODO: Clean this up
					ThreadPool.QueueUserWorkItem(new WaitCallback(HandleCallback), callback);
				}

				Thread.Sleep(_sleep);
			}
		}
	}
}