#include "QrfePipe.h"

#include <QTimer>

QrfePipe::QrfePipe(QObject *parent)
	: QIODevice(parent)
	, m_name("Pipe")
	, m_otherPipe(0)
{
	connect(&m_inputBuffer,		SIGNAL(readyRead()),
			this,				SIGNAL(readyRead()) );

	m_inputBuffer.open(QIODevice::ReadWrite);
}

QrfePipe::QrfePipe(QString name, QObject *parent)
	: QIODevice(parent)
	, m_name(name)
	, m_otherPipe(0)
{
	connect(&m_inputBuffer,		SIGNAL(readyRead()),
			this,				SIGNAL(readyRead()) );

	m_inputBuffer.open(QIODevice::ReadWrite);
}

QrfePipe::~QrfePipe()
{
	m_inputBuffer.close();
}

bool QrfePipe::connectToPipe ( QrfePipe* pipe )
{
	if(this->isConnected() || pipe->isConnected())
		return false;

	this->m_otherPipe = pipe;
	pipe->m_otherPipe = this;

	QIODevice::open(QIODevice::ReadWrite);
	m_name = pipe->m_name;

	QTimer::singleShot(0, pipe, SLOT(remoteConnect()) );

	emit connected();

	return true;
}

QString	QrfePipe::name () const
{
	return m_name;
}

bool QrfePipe::isConnected () const
{
	return isOpen();
}

void QrfePipe::close ()
{
	if(isOpen()){
		QIODevice::close();
		emit disconnected();
	}
	if(m_otherPipe){
		QTimer::singleShot(0, m_otherPipe, SLOT(remoteDisconnect()) );
	}

	m_otherPipe = 0;
}

qint64 QrfePipe::bytesAvailable () const
{
	return m_inputBuffer.bytesAvailable();
}

qint64 QrfePipe::readData ( char * data, qint64 maxSize )
{
	return m_inputBuffer.read(data, maxSize);
}

qint64 QrfePipe::writeData ( const char * data, qint64 maxSize )
{
	if(m_otherPipe)
		return m_otherPipe->m_inputBuffer.write(data, maxSize);
	else
		return 0;
}

void QrfePipe::remoteConnect ( )
{
	if(!isOpen())
	{
		QIODevice::open(QIODevice::ReadWrite);
		emit connected();
	}
}

void QrfePipe::remoteDisconnect ( )
{
	if(isOpen())
	{
		QIODevice::close();
		emit disconnected();
	}
	m_otherPipe = 0;
}
