#include "netbuffer"
#include "SocketHandling/socket/socket"

unsigned Netbuffer::netread (Socket &s, unsigned timeout) {
    PROFILE("Netbuffer::netread");

    // debugmsg("Reading from fd " << s.fd() << ", timeout "
    //           << timeout << "\n");
    if (timeout) {
	Fdset set(timeout);
	set.add(s);
	set.wait_r();
	if (! set.readable(s)) {
	    msg("Fd "<< s.fd() << " failed to become readable within " <<
		timeout << " sec\n");
	    return 0;
	}
    }

    check_space(config.buffersize());

    // Read from the network. If this fails, don't throw an exception
    // because it's quite common (too much logging otherwise).
    ssize_t nread = read (s.fd(), buf_data + buf_sz, config.buffersize());
    if (nread < 0) {
	msg("Read failed on fd " << s.fd() + ": " << strerror(errno) << '\n');
	return 0;
    }
    buf_sz += nread;

    if (config.debug() && nread) {
        ostringstream o;
        o << "Got " << nread << " bytes from fd " << s.fd()
	  << ", timeout " << timeout << ": ";
        for (unsigned i = 0; i < (unsigned)nread; i++)
            o << printable(buf_data[i]);
        o << "\n";
        debugmsg (o.str());
    }

    return nread;
}
