//
// C++ Implementation: client
//
// Description: 
//
//
// Author: Konrad Rosenbaum <konrad@silmor.de>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include "client.h"

#include <QTcpSocket>
#include <QTextEdit>
#include <QLineEdit>
#include <QScrollBar>
#include <QMenuBar>
#include <QMenu>
#include <QVBoxLayout>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>

CClient::CClient(QString host,int port,QWidget*p)
	:QMainWindow(p)
{
	//create menu
	QMenu*m=menuBar()->addMenu("&Client");
	m->addAction("Clear &Display",this,SLOT(clearDisplay()));
	m->addAction("&Save Display as...",this,SLOT(dumpFile()));
	m->addAction("D&isconnect client",this,SLOT(doDisconnect()));
	m->addSeparator();
	m->addAction("&Close Client Window",this,SLOT(close()));
	setAttribute(Qt::WA_DeleteOnClose);
	//main widget
	QWidget*w=new QWidget;
	setCentralWidget(w);
	QVBoxLayout*vl;
	w->setLayout(vl=new QVBoxLayout);
	vl->addWidget(text=new QTextEdit,2);
	vl->addWidget(line=new QLineEdit,0);
	text->setText("connecting...");
	text->setReadOnly(true);
	text->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
	line->setReadOnly(true);
	connect(line,SIGNAL(returnPressed()),this,SLOT(sendStuff()));
	//connect
	sock=new QTcpSocket(this);
	connect(sock,SIGNAL(connected()),this,SLOT(connSock()));
	connect(sock,SIGNAL(disconnected()),this,SLOT(dconSock()));
	connect(sock,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(dconSock()));
	connect(sock,SIGNAL(readyRead()),this,SLOT(readSock()));
	sock->connectToHost(host,port);
}

CClient::~CClient()
{
	//close the socket
	if(sock)
		sock->close();
}

void CClient::connSock()
{
	//set display to correct mode
	text->setText("Connected.");
	line->setReadOnly(false);
}

void CClient::dconSock()
{
	//make sure there are no more signals from the socket
	sock->disconnect();
	//disconnect & delete
	sock->close();
	sock->deleteLater();
	sock=0;
	//lock line edit
	line->setReadOnly(true);
	//inform user
	QMessageBox::warning(this,"Disconnected","The connection has been closed.");
}

void CClient::readSock()
{
	//receive
	buf+=QString::fromUtf8(sock->readAll());
	//set display
	text->setText(buf);
	//scroll to end
	QScrollBar*sb=text->verticalScrollBar();
	if(sb){
		sb->setValue(sb->maximum());
	}
}

void CClient::doDisconnect()
{
	sock->disconnectFromHost();
}

void CClient::dumpFile()
{
	//get a file name
	QString fn=QFileDialog::getSaveFileName(this,"Save Log as...");
	if(fn=="")return;
	//create file
	QFile fd(fn);
	if(!fd.open(QIODevice::WriteOnly|QIODevice::Truncate)){
		QMessageBox::warning(this,"Error","Unable to write to file.");
		return;
	}
	fd.write(buf.toLocal8Bit());
	fd.close();
}

void CClient::clearDisplay()
{
	text->setText("");
	buf="";
}

void CClient::sendStuff()
{
	//sanity check
	if(!sock)return;
	//send
	sock->write(QString(line->text().trimmed()+"\n").toUtf8());
	//clear line
	line->setText("");
}
