#include "ChatClient.h"
#include "MainWindow.h"

ChatClient::ChatClient(MainWindow *mainWindow, QObject *parent)
	: QTcpSocket(parent)
	, mainWindow(mainWindow)
{
	// Server connections
	connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater()));

	// Client connections
	connect(this, SIGNAL(connected()), mainWindow, SLOT(connectionEstablished()));
	connect(this, SIGNAL(disconnected()), mainWindow, SLOT(connectionLost()));
//	connect(this, SIGNAL(error(QAbstractSocket::SocketError)), mainWindow, SLOT(networkError()));

	// Both modes connections
	connect(this, SIGNAL(readyRead()), this, SLOT(dataReceived()));

	// Send data
	connect(mainWindow, SIGNAL(sendMessage(QString)), this, SLOT(sendData(QString)));
}

void ChatClient::dataReceived()
{
	QString text = readLine();
	mainWindow->dataReceived(text);
	qDebug("Data received: \"%s\"", qPrintable(text));
}

void ChatClient::sendData(const QString& text)
{
	write( text.toUtf8() );
	qDebug("Data sent: \"%s\"", qPrintable(text));
}
