#include "cselect.h"

#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>

cTBSelect::cTBSelect(void) {
	Clear();
}

cTBSelect::~cTBSelect() {
}

void cTBSelect::Add(int Filed, bool Output /* = false */) {
	if (Output)
		FD_SET(Filed, &m_Wfds);
	else
		FD_SET(Filed, &m_Rfds);

	if (Filed > m_MaxFiled)
		m_MaxFiled = Filed;
}

void cTBSelect::Clear(void) {
	FD_ZERO(&m_Rfds);
	FD_ZERO(&m_Wfds);
	m_MaxFiled = -1;
}

int cTBSelect::Select(int TimeoutMs) {
	struct timeval tv;

	if (TimeoutMs != -1) {
		tv.tv_usec = (TimeoutMs % 1000) * 1000;
		tv.tv_sec  = TimeoutMs / 1000;
	}

	return ::select(m_MaxFiled + 1, &m_Rfds, &m_Wfds, 0, TimeoutMs != -1 
			?  &tv : 0);
}

