#include <stdio.h>
#include <sched.h>
#include <unistd.h>
#include <time.h>
#include <list>
#include "Connector.h"
#include "ConnectionWrap.h"
#include "BufferedFile.h"
#include "BufferedFileFactory.h"
#include "ConnectionFactory.h"
#include "OutputConnection.h"
#include "Clock.h"

/**
 * The default port to listen on for the DeMuxer
 */
#define DEFAULT_PORT 8880

/**
 * Accepts 1 arguement of a port
 */
int main(int argc, char *argv[]){
	BufferedFileFactory * bf = new BufferedFileFactory();
	ConnectionFactory * cf = NULL;
	BufferedFile * outputBf = bf->getNewBufferedFile(STDOUT_FILENO);
	outputBf->setWriteOnly();
	OutputConnection<short> * oc = new OutputConnection<short>(outputBf);
	ConnectionWrap * ocwrap = new ConnectionWrap((void*)oc,SHORTCONN);
	list<ConnectionWrap *> * incoming = new list<ConnectionWrap*>();
	if (argc > 1) {
		cf = new ConnectionFactory(bf,atoi(argv[1]),0,0,0);
	} else {
		cf = new ConnectionFactory(bf,DEFAULT_PORT,0,0,0);
	}
	try {
		for (;;) {
			int rw = bf->process(100);
			if (rw) {
				Clock::clock++;
				//cerr << ".";
				ocwrap->process();
				if (cf->isThereANewConnection()) {
					cerr << "_";
					ConnectionWrap * wrap = cf->processConnection();
					if (wrap!=NULL) {
						cerr << (int)(wrap->conn.floatConn->getFileHandle()) << "\n";
						assert(wrap->conn.floatConn!=0);
						if (wrap == NULL) {
							cerr << "NULL Wrapper Returned?\n";
						} else {
							cerr << "New Connection\n";
							incoming->push_back(wrap);
							ocwrap->connectFrom(wrap);
						} 
					} else {
						cerr << "Connection Failed!\n";
					}
				}
			}
		}
	} catch (char * str) {
		cerr<< "EXCEPTION: " <<str<<"\n";
	} catch (string * str) {
		cerr<< "EXCEPTION: " <<*str<<"\n";
	}
	return 0;
}
