using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using VRepProxy.Objects;

namespace VRepProxy.Proxy
{
	public class VRepProxy
	{
		private static UdpClient udpClient;
		private static IPEndPoint endPoint;
		private static String host;
		private static int port;

		private const int socketReadDelay = 30;

		private Scene scene;

		public VRepProxy(String host, int port){
			VRepProxy.host = host;
			VRepProxy.port = port;
			Connect ();
		}

		public static void Connect()
		{
			if (udpClient == null || endPoint == null) {
				udpClient = new UdpClient ();
				udpClient.Client.ReceiveBufferSize = 1024;
				endPoint = new IPEndPoint (IPAddress.Parse (host), port);
			}
			udpClient.Connect (endPoint);
		}

		public static void ReleaseConnection()
		{
			if (udpClient == null || endPoint == null) {
				udpClient.Close ();
			}
		}

		public Scene GetScene(){
			if (scene == null) {
				scene = new Scene ();
			}
			return scene;
		}

		public static Boolean Perform(String command){
			//Connect ();
			byte[] sendByte = Encoding.ASCII.GetBytes (command);

			udpClient.Send (sendByte, sendByte.Length);
			//while (true) {
			//	try {
			//		var receivedData = udpClient.Receive (ref endPoint);
			//		String data = Encoding.ASCII.GetString (receivedData);
			//		if (data.Contains ("[executed]")) {
			//			success = true;
			//			break;
			//	    } 
			//	} catch (System.Net.Sockets.SocketException ex) {
			//		if (ex.ErrorCode != 10060) {
			//			success = false;
			//			break;
			//		}
			//	}
			//	System.Threading.Thread.Sleep (socketReadDelay);
			//}
			//ReleaseConnection ();

			// A better treatment that command was executed has to be done
			// here.
			return true;
		}

		public static String Get(String command){
			//Connect ();
			String sensors = null;

			byte[] sendByte = Encoding.ASCII.GetBytes (command);
			udpClient.Send (sendByte, sendByte.Length);

			while (true) {
				try {
					var receivedData = udpClient.Receive (ref endPoint);
					String data = Encoding.ASCII.GetString (receivedData); 
					//if (data.Contains ("[executed]")) {
						sensors = data.Substring (0, data.IndexOf (Environment.NewLine));
						break;
					//} 
				} catch (System.Net.Sockets.SocketException ex) {
					if (ex.ErrorCode != 10060) {
						break;
					}
				}
				System.Threading.Thread.Sleep (socketReadDelay);
			}
			//ReleaseConnection ();
			return sensors;
		}
	}

}