#include "common/fusebox.h"
#include "common/packet.h"
#include "common/utils.h"

int main(int argc, char **argv)
{
    progname = argv[0];

    Fusebox fb;
    Packet *p;
    int new_connection,
	written = 0,
	counter = 0;

    
    while (1)
    {
	new_connection = fb.check_new_connection();

	for (int i = 0; i < fb.get_nr_plugs(); i++)
	{
	    if (fb[i])
	    {
		p = read_packet(fb[i]);

		if (p)
		{
		    if (p->err)
		    {
			warning("pulling plug %d from the socket", i);
			fb.close_connection(i);
		    }
		    else
		    {
			print_packet(p);
			if (p->get_type() == TYPE_INFO_STRING)
			    if (!strcmp(((Packet_info_string *)p)->get_string(), "quit"))
			    {
				// shut down the server
				warning("quit requested: pulling plug %d", i);
				fb.close_connection(i);
			    }
		    }
		    delete p;
		}
	    }
	}

	if (!(counter % 100))
	{
	    for (int i = 0; i < fb.get_nr_plugs(); i++)
	    {
		if (fb[i])
		{
		    written = Packet_info_string::write_to(fb[i],
							   21,
							   43,
							   12,
							   "antwoord :)");
		    
		    if (written < 0)
		    {
			warning("pulling plug %d from the socket", i);
			fb.close_connection(i);
		    }
		}
	    }
	}
	
	usleep(10000);
	counter++;
    }

    return 0;
}
