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

namespace WorldOfPeacecraft
{
	public class Buffer
	{
		private Queue<string> Lines = new Queue<string>();
		private int MaxSize;
		private AutoResetEvent QueueFullLock = new AutoResetEvent(false);
		private AutoResetEvent QueueEmptyLock = new AutoResetEvent(false);

		public Buffer (int maxSize)
		{
			this.MaxSize = maxSize;
		}

		public void AddLine (string line)
		{
			bool waitRequired = false;
			lock (Lines) {
				if (Lines.Count >= MaxSize) {
					waitRequired = true;
					QueueFullLock.Reset ();
				}
			}
			if (waitRequired) {
				QueueFullLock.WaitOne ();
			}
			lock (Lines) {
				Lines.Enqueue (line);
				QueueEmptyLock.Set();
			}
		}

		public string NextLine ()
		{
			bool waitRequired = false;
			string line;
			lock (Lines) {
				if (Lines.Count == 0) {
					waitRequired = true;
					QueueEmptyLock.Reset ();
				}
			}
			if (waitRequired) {
				QueueEmptyLock.WaitOne ();
			}
			lock (Lines) {
				line = Lines.Dequeue();
				QueueFullLock.Set ();
			}
			return line;
		}
	}
}
