#ifndef QSOCKETNOTIFY_FACTORY_H
#define QSOCKETNOTIFY_FACTORY_H


#include <QSocketNotifier>
#include <stdio.h>
#include <sys/socket.h>


class SocketNotifier : public QObject
{
    Q_OBJECT
public:
    SocketNotifier(int socket, int type, QObject *parent=0) {
        fd = socket;
        t = type;
	if ( type != 2 )
		printf("unsupported socket notifier type\n");
        sn_read = new QSocketNotifier(socket, (QSocketNotifier::Type)0, parent);
        sn_hup = new QSocketNotifier(socket, (QSocketNotifier::Type)2, parent);
        connect(sn_read, SIGNAL(activated(int)), this, SLOT(callbackDispatchRead(int)));
        connect(sn_hup, SIGNAL(activated(int)), this, SLOT(callbackDispatchHup(int)));
	printf("created SocketNotifier for fd: %i, type: %i\n", socket, type);
	sn_read->setEnabled(true);
	sn_hup->setEnabled(true);
    }
    ~SocketNotifier() { delete sn_read; delete sn_hup; }
    int socketDescriptor() { return fd; }
public slots:
    void callbackDispatchRead(int x) {
	char tmp[3];	
	if ( ::recv(fd, tmp, 1, MSG_PEEK) ) 
        	emit activated2(fd,0);
	else
        	emit activated2(fd,2);
    }
    void callbackDispatchHup(int x) {
        emit activated2(fd,2);
    }
signals:
    void activated2(int,int);
private:
    int fd, t;
    QSocketNotifier *sn_read;
    QSocketNotifier *sn_hup;
};


class SocketNotifierFactory : public QObject
{
    Q_OBJECT
public slots:
    SocketNotifier *new_SocketNotifier(int socket, int type, QObject *parent=0) { return new SocketNotifier(socket,type,parent); }
    int fd(SocketNotifier *sn) { return sn->socketDescriptor(); }
};


#endif

