/*
 * QrfeProtocolHandler.h
 *
 *  Created on: 14.05.2009
 *      Author: stefan.detter
 */

#ifndef QRFEPROTOCOLHANDLER_H_
#define QRFEPROTOCOLHANDLER_H_

#include <QObject>
#include <QIODevice>
#include <QStringList> 
#include <QThread>
#include <QBuffer>
#include <QMutex>

#ifdef QT_NETWORK_LIB
	#include <QTcpSocket>
	#include <QLocalSocket>
#endif

#include <QrfeTrace>

#include <QrfeFifo>
#include <QrfeMessageQueue>
#include <QrfeProtocolHandlerGlobal>

class QrfeProtocolHandler :
	public QThread,
	protected QrfeTraceModule
{
	Q_OBJECT
public:
	QrfeProtocolHandler(QIODevice* dev, QrfeGlobal::DeviceType deviceType, QObject* parent = 0);
	virtual ~QrfeProtocolHandler();

	QString 				deviceName() const;
	QrfeGlobal::DeviceType	deviceType() const;

signals:
	void deviceClosed();

public:
	bool deviceRemoved();
	void setTimeOut(uint timeOut);

public slots:
	virtual void deleteLater();
	virtual void deviceWasRemoved();

	void releaseDeviceImmediatly();

protected:
	virtual void run ();

	virtual void computeData 	( const QByteArray &data );
	virtual void computeMessage ( const QByteArray &msg );

	bool send ( const QByteArray &data );

	bool waitForNoOneWaiting(uint msecs = 0);

protected slots:
	void readFromDevice();
	void sendToDevice();

private:
	QString 	getDeviceSpecificName();
	qint64 		writeDeviceSpecific(const QByteArray &data);
	QByteArray 	readAllDeviceSpecific();
	void 		flushDeviceSpecific();
	void 		connectDeviceSpecific();

private slots:
	#ifdef QT_NETWORK_LIB
		void tcpSocketError ( QAbstractSocket::SocketError socketError );
		void localSocketError ( QLocalSocket::LocalSocketError socketError );
	#endif

protected:
	QIODevice* 					m_device;
	QrfeGlobal::DeviceType 		m_deviceType;

	QrfeFifo*					m_sendBuffer;

	QString						m_deviceName;

	QrfeMessageQueue			m_messageQueue;

	bool						m_threadInitialized;
	bool 						m_classInitialized;

	uint 						m_MAX_WAIT_TIME_IN_MS;
	bool						m_deviceRemoved;

public:
	static uint 				_traceLevel;
	static Priority 			_priority;
	static bool 				_emitISRsQueued;
};

#endif /* QRFEPROTOCOLHANDLER_H_ */
