#ifndef SEARCHTHREAD_H
#define SEARCHTHREAD_H

#include "client.h"
#include "marshallinghelper.h"
#include <kdebug.h>
#include <qthread.h>
#include "kwestsearchthread_dcopiface.h"
#include <qcstring.h>
#include <qobject.h>
#include <qmutex.h>
#include <qdict.h>

typedef QDict<int> ClientList;

class SearchThread : public QThread ,  virtual public KwestSearchThreadDCOPIface
{
    public:
		SearchThread(QObject * o , const QString & query , QString  socketPath ,
			  QDict <ClientList> * QueryList ,
			  const bool &peer2peer ):
				    DCOPObject((QCString) query), 
		    		    KwestSearchThreadDCOPIface(),
		    		    QThread(),
		    		    m_receiver(o),
	    	    		    m_query(query),
	    	    		    m_socketPath(socketPath),
	    	    		    m_byteResults(),
	    	    		    m_peer2peer(peer2peer) { }
		
    		virtual ~SearchThread()
		{
			terminate ();
			wait ();
		}

		//thread stuff
    		virtual void run() = 0;
		
		// common code ... share it across all backends
		//transferes binary data, whatever they are to the server
		//i.e the client waiting for a response to its query
		virtual void runTransfer(QString socketPath , QByteArray &byteData)
		{
			kdDebug() << "SearchThread::runTransfer to socket: " << socketPath << endl;

			//for the transfer, the search-daemon is a client and the query-client is the server here
			m_hitsSocket = new Client ( (QCString) socketPath); //FIXME:
			int ok = m_hitsSocket->init();
			if (! (ok > 0) )
			{
				kdDebug() << "SearchThread::runTransfer init client finished: BAD CONNECTION"<< endl;
				delete m_hitsSocket;
				return;
			}
			
			kdDebug() << "SearchThread::runTransfer init client finished: "<< endl;
			
			//FIXME:is it usefull to compress data ?
			QByteArray qByteData = qCompress( byteData );
			byteData.resize(0);
			m_hitsSocket->BigRawDataServerToCLient( qByteData , 1000);

			//tell server, that sending is finished
			m_hitsSocket->sendSignal((QString) "The End");
			
			//FIXME: blocking wait until the server responds correctly
			m_hitsSocket->getSignal((QString) "The End");
			
			kdDebug() << "SearchThread::runTransfer finished: "<< endl;

			delete m_hitsSocket;
		}

		//virtual void encodeHits( void* list_hits ) = 0;
		
		//dcop interface. Not used so far
    		virtual bool isRunning() const
		{
			return this->running ();
		}

		//dcop interface. Not used so far
		virtual bool isFinished() const
		{
			return this->finished();
		}

		
		
	protected:
		QMutex mutex;
		QObject *                              m_receiver;
		QString                                m_query;
		QString                                m_socketPath;
		QDict <ClientList> *                   m_queryList;
		
		Client *			       m_hitsSocket;
		QByteArray                             m_byteResults;
		
		bool m_peer2peer;
};

#endif
