#include <QtGui>
#include <QtNetwork\QtNetwork>

#include "tcpclient.h"

TcpClient::TcpClient(QWidget *parent) : QWidget(parent)
{
	tcpSocket = new QTcpSocket(this);

	connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readAnswer()));
	connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));

	QPushButton *bla = new QPushButton("test");

	connect(bla, SIGNAL(clicked()), this, SLOT(tcpConnect()));

	QGridLayout *mainLayout = new QGridLayout;

	mainLayout->addWidget(bla, 0, 0);

	setLayout(mainLayout);
	show();
}

void TcpClient::tcpConnect()
{
	blockSize = 0;
	tcpSocket->abort();
	tcpSocket->connectToHost("localhost", 49363);
}

void TcpClient::createNewAccount()
{
	
}

void TcpClient::login()
{

}

void TcpClient::readAnswer()
{
	QMessageBox::information(0, tr("ProjektZ"), tr("Server error, please try again."));
	QDataStream in(tcpSocket);
	in.setVersion(QDataStream::Qt_4_0);

	if (blockSize == 0)
	{
		if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
		{
			return;
		}

		in >> blockSize;
	}

	if (tcpSocket->bytesAvailable() < blockSize)
	{
		return;
	}

	QString answer;
	in >> answer;
}

void TcpClient::displayError(QAbstractSocket::SocketError socketError)
{
	switch (socketError)
	{
		case QAbstractSocket::RemoteHostClosedError:
			QMessageBox::information(0, tr("ProjektZ"), tr("Server error, please try again."));
			break;
	
		case QAbstractSocket::HostNotFoundError:
			QMessageBox::information(0, tr("ProjektZ"), tr("Host was not found, please check your network settings."));
			break;
	
		case QAbstractSocket::ConnectionRefusedError:
			QMessageBox::information(0, tr("ProjektZ"), tr("Connection refused, please check your firewall."));
			break;
	
		default:
			QMessageBox::information(0, tr("ProjektZ"), tr("The following error occurred: %1.").arg(tcpSocket->errorString()));
	}
}