/*
 *
 *   unixclient.cc
 *
 */


#include <iostream>
#include <string>
#include <list>
#include <my++/muxunixsocket.h>
#include <my++/muxtty.h>
#include <my++/multiplex.h>

#include <my++/termios.h>
#include <my++/serialios.h>
#include <my++/conios.h>

#include <cstring>
#include <cstdio>

using namespace std;

const int default_flags = my::device::not_ctl_tty | my::device::nonblocking;

#define REMOTE_ADDR "testsocket"


/*
 *
 *   main (...)
 *
 */

int main (int argc, char **argv) {
	my::multiplexed::unixsocket sock;
	my::multiplexed::tty console;
	my::multiplex mux;
	char buffer [128];
	int count, rtn;

	my::termios console_config;

	try {
		console.open("/dev/tty", default_flags);
		console.set_options (console_config);
	} catch (const std::exception &e) {
		cerr << "Error opening /dev/tty: " << e.what() << endl;
		return 1;
	}

	cerr << "Try to connect to socket \'" << REMOTE_ADDR << "\': ";
	cerr.flush();

	try {
		sock.connect(REMOTE_ADDR);
	} catch (const std::exception &e) {
		cerr << "Error opening socket: " << e.what() << endl;
		return 1;
	}

	cerr << "Success!\r\n\n";

	/* */
	mux.add(sock);
	mux.add(console);

	for (;;) {
		rtn = mux.watch();

		if (rtn > 0) {
			if (console.closed()) {
				console.close();
				sock.close();
				return 0;
			}

			if (sock.disconnected()) {
				console.close();
				sock.close();
				return 0;
			}

			while (console.ready()) {
				count = console.get(buffer, sizeof(buffer));
				cerr << "Read " << count << " bytes from CONSOLE.\r\n";
				if (buffer[0] == 3)
					return 0;
				if (count > 0)
					sock.put(buffer, count);
			}

			while (sock.ready()) {
				count = sock.get(buffer, sizeof(buffer));
				cerr << "Read " << count << " bytes from SOCKET.\r\n";
				if (count > 0)
					console.put(buffer, count);
			}
		}
	}


	/* should never reach here */
	return 0;
}
