using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;

namespace WorldOfPeacecraft
{
	class Receiver
	{
		private TcpClient Client;
		private StreamReader Reader;
		private Buffer ReceiverBuffer;
		private Thread ReceiverThread;

		public Receiver (TcpClient client, Buffer buffer)
		{
			this.Client = client;
			this.ReceiverBuffer = buffer;
			ReceiverThread = new Thread(new ThreadStart(this.doReceive));
		}

		public string Receive ()
		{
			return Reader.ReadLine ();
		}

		private void doReceive ()
		{
			this.Reader = new StreamReader (Client.GetStream ());
			try {
				while (true) {
					ReceiverBuffer.AddLine (Receive ());
				}
			} catch (ObjectDisposedException e) {
				// Nothing to do
			} catch (IOException e) {
				// Nothing to do
			}
		}

		public void Start()
		{
			ReceiverThread.Start ();
		}
	}
}
