#include "socket.h"
#include "socket_stream.h"
#include "async.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
	astream ast;
	string winch_buffer;
	string level_wind_buffer;

	tcp_client_socket winch(endpoint("localhost",4711));
	tcpstream winch_stream(winch);

	tcp_client_socket level_wind(endpoint("localhost",4712));
	tcpstream level_wind_stream(level_wind);

	for (int i = 0; i < 4; i++) {
		try {
			ast(winch_stream) << "Hello from Elmo Manager" << endl;
			ast(level_wind_stream) << "Hello from Elmo Manager" << endl;
			ast.wait();
			ios_base *b = ast.wait(5000);
			ast(winch_stream) >> winch_buffer;
			ast(level_wind_stream) >> level_wind_buffer;
			if (b == &winch_stream) {
				cout << "Winch : " << winch_buffer << endl;
			} else if (b == &level_wind_stream) {
				cout << "Level Wind: " << level_wind_buffer << endl;
			} else if (b == 0) {
				cout << "Timeout" << endl;
				ast.abort();
				if (ast.wait(5000)==0)
					cout << "Abort failed\n";
				else
					cout << "Abort succeeded\n";
				break;
			}
			else
				cout << "Strange return from wait\n";
		}
		catch (async_error& e) {
			cout << "Async error " << e.what() << endl;
			cout << (e.whatios()== &winch_stream ? "Winch" : e.whatios()==&level_wind_stream ? "Level Wind" : "?") << endl;
		}
		catch (runtime_error & e) {
			cout << "Runtime error " << e.what() << endl;
		}
	}
	return 0;
}


#if 0
int frobner()
{
	astream ast;

	string buf1;
	string buf2;
	ios_base *p;

	tcp_listener t1(4711);
	tcp_socket s1 = t1.accept();


	tcp_listener t2(4712);
	tcp_socket s2 = t2.accept();
	tcpstream ts2(s2);

	ast(ts1) >> buf1;
	ast(ts2) >> buf2;
	do  {
		try {
			p = ast.wait();
			if (p == &ts1) {
				ast(ts1) << "4711: " << buf1 << endl;
//				ast(ts1) >> buf1;
			}
			else if (p == &ts2) {
				ast(ts2) << "4712: " << buf2 << endl;
//				ast(ts2) >> buf2;
			}
			else
				cout << "Strange return from wait\n";
		}
		catch (async_error& e) {
			cout << "Async error " << e.what() << endl;
//			cout << (e.whatios()==&cin ? "cin" : e.whatios()==&ts ? "ts" : "?") << endl;
//			if (ast.wait()==&cin)
//				cout << "Read " << x << endl;
		}
		catch (runtime_error & e) {
			cout << "Runtime error " << e.what() << endl;
		}
	} while (p);


	return 0;
}
#endif

