using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using NmeaParser;

namespace skyscraper5.NmeaSharpWrapper
{
	internal class GpsdClient : NmeaSharpWrapper
	{
		public GpsdClient(string hostname, ushort port)
		{
			this.hostname = hostname;
			this.port = port;
		}

		private string hostname;
		private ushort port;
		protected override void ProcessorThread()
		{
			TcpClient tc = new TcpClient();
			tc.Connect(hostname, port);
			NetworkStream networkStream = tc.GetStream();
			StreamWriter streamWriter = new StreamWriter(networkStream);
			streamWriter.WriteLine("?WATCH={\"enable\":true,\"nmea\":true}");
			streamWriter.Flush();

			StreamDevice streamDevice = new StreamDevice(networkStream);
			streamDevice.MessageReceived += HandleNmeaMessage;
			streamDevice.OpenAsync().Wait();
			CancelRequest = false;
			while (!CancelRequest)
			{
				Thread.Sleep(1000);
			}

			streamDevice.CloseAsync().Wait();
			streamWriter.Close();
			networkStream.Close();
			tc.Close();
		}
	}
}
