////////////////////////////////////////////////////////////
//
//     	Definition of a class
//	ASocketMonitor
//
//      Copyright 2002 
//
////////////////////////////////////////////////////////////

#include <pthread.h>
#include <string.h>
#include "ASocketMonitor.h"

	// ASocketMonitor

ASocketMonitor::ASocketMonitor():
max_handle(0)
{
	FD_ZERO(&read_set);
	FD_ZERO(&write_set);
	FD_ZERO(&error_set);	
}


int ASocketMonitor::add_send(ASocket& z)
{
	int h=z.get_handle();
	if(h>max_handle) max_handle=h;
	
	FD_SET(h,&write_set);
	
	return 0;
}

int ASocketMonitor::add_receive(ASocket& z)
{
	int h=z.get_handle();
	if(h>max_handle) max_handle=h;
	
	FD_SET(h,&read_set);

	return 0;
}

int ASocketMonitor::add_error(ASocket& z)
{
	int h=z.get_handle();
	if(h>max_handle) max_handle=h;
	
	FD_SET(h,&error_set);

	return 0;
}


int ASocketMonitor::add_accept(ASocket& z)
{
	int h=z.get_handle();
	if(h>max_handle) max_handle=h;
	
	FD_SET(h,&read_set);

	return 0;
}

int ASocketMonitor::remove(ASocket& z)
{
	int h=z.get_handle();
	
	FD_CLR(h,&read_set);
	FD_CLR(h,&write_set);
	FD_CLR(h,&error_set);
	
	return 0;
}


// blocks until an event or timeout
int ASocketMonitor::monitor(int& n,unsigned milliseconds)
{
        timeval t;
        t.tv_sec=milliseconds/1000;
        t.tv_usec=(milliseconds-t.tv_sec*1000)*10; // microseconds

        n=select(max_handle+1,&read_set,&write_set,&error_set,&t);

        if(n>=0) return 0;  
        
        n=0;     

        return 1;               
}