#include "socket.h"

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <sys/types.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif

#include <ctype.h>
#include <netdb.h>
#include <sys/utsname.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/ioctl.h>
#ifdef HAVE_SYS_FILIO_H
#include <sys/filio.h> // for FIONREAD
#endif
#include "netutils.h"

Socket::Socket(int fd, bool createNotifier, QObject *parent, const char *name)
: _fd(fd), _notifier(0)
{
	if (createNotifier) {
		ASSERT( _fd!=-1 );
		_notifier = new QSocketNotifier(fd, QSocketNotifier::Read, parent, name);
		_notifier->setEnabled(FALSE);
	}
}

Socket::~Socket()
{
	if (_notifier) delete _notifier;
	if ( _fd!=-1 ) closeSocket(_fd);
}

bool Socket::write(const QByteArray &a)
{
	ASSERT( _fd!=-1 );
	return ( ::write(_fd, a.data(), a.size())==(int)a.size() );
}

bool Socket::write()
{
	bool res = write(writing.buffer());
	writing.clear();
	return res;
}

int Socket::pendingData() const
{
	ASSERT( _fd!=-1 );
	int size = 0;
	if ( ioctl(_fd, FIONREAD, (char *)&size)<0 ) return -1;
	return size;
}

int Socket::read()
{
	ASSERT( _fd!=-1 );
	reading.clearRead();
	
	int size = pendingData();
	if ( size==-1 ) return -1;
	
	reading.device()->close();
	int dec = reading.size();
	reading.buffer().resize(dec + size);
	size = ::read(_fd, reading.buffer().data() + dec, size);
	if ( size==-1 ) reading.buffer().resize(dec);
	reading.device()->open(IO_ReadOnly);
	
	return size;
}
