using System;
using System.IO.Ports;
using System.IO;

using libscomp;

namespace mono_scomp_demo
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			Scomp.ErrorCode err;
			SerialPort sp = new SerialPort ();
			Scomp sc;
			bool remote = true;

			if (args.Length == 0) {
				switch (Environment.OSVersion.Platform) {
				case PlatformID.Unix:
				case PlatformID.MacOSX:
					sp.PortName = "/dev/ttyACM0";
					break;
				default:
					sp.PortName = "COM1";
					break;
				}
			} else
			if (args.Length == 1) {
				sp.PortName = args [0];
			} else
			if (args.Length == 2 && args [0].CompareTo ("-s") == 0) {
				remote = false;
				sp.PortName = args [1];
			} else {
				Console.WriteLine("invalid parameters");
				return;
			}

				

			sp.BaudRate = 115200;
			sp.Handshake = Handshake.None;
			sp.StopBits = StopBits.One;
			sp.DataBits = 8;

			try {
				sp.Open ();
			} catch (Exception ex) {
				Console.Write ("Could not open " + sp.PortName + ": ");
				Console.WriteLine (ex.Message);
				return;
			}

			Console.WriteLine ("Opened " + sp.PortName);

			sc = new Scomp (sp.BaseStream);

			string req;
			string resp;


			if (remote) {
				while (true) {

					req = Console.In.ReadLine ();
					if (req == null)
						break;
					req.TrimEnd (Environment.NewLine.ToCharArray ());
					Console.WriteLine("Q:"+req);
					err = sc.Exchange (req, out resp, 2000);
					if (Scomp.ErrorCode.SCOMP_ERR_OK == err) {
						Console.WriteLine ("R:" + resp);
					} else {
						Console.WriteLine ("ERR:" + err);
					}

				}
			} else {
				char type;
				int seq;
				while (!Console.KeyAvailable){
					err = sc.Recv(out resp,out type,out seq,50);
					if (Scomp.ErrorCode.SCOMP_ERR_OK == err){
						sc.Seq = seq;
						Console.WriteLine(type+":"+resp);
						Console.WriteLine("R:ok");
						sc.Send("ok",'R');
					}
				}
			}
			sp.Close();
		}
	}
}
