#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "ConnectDialog.h"

MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent)
	, ui(new Ui::MainWindow)
	, connectDialog(NULL)
{
	ui->setupUi(this);
	connect( ui->actionConnect, SIGNAL(triggered(bool)), this, SLOT(newConnection()) );
	connect( ui->buttonSend, SIGNAL(clicked()), this, SLOT(buttonSendPressed()) );
}

MainWindow::~MainWindow()
{
	delete ui;
}

QString MainWindow::getUserNickname() const
{
	Q_ASSERT(connectDialog);
	return connectDialog->getUserNickname();
}

void MainWindow::newConnection()
{
	if ( ! createConnectDialog() ) return;

	// Show the dialog, if it is already shown, this call has no effect
	connectDialog->show();

	// If dialog is already shown, make it top and active
	connectDialog->raise();
	connectDialog->activateWindow();
}

void MainWindow::dataReceived(const QString& text)
{
	ui->whiteBoard->append(text);
}

void MainWindow::connectionEstablished()
{
	ui->inputMessage->setEnabled(true);
	ui->buttonSend->setEnabled(true);
	qDebug("Connection established");
}

void MainWindow::connectionLost()
{
	ui->inputMessage->setEnabled(false);
	ui->buttonSend->setEnabled(false);
	qDebug("Connection lost");
}

bool MainWindow::createConnectDialog()
{
	// If already created, done
	if ( connectDialog ) return true;

	// Create a dialog and test for success
	connectDialog = new ConnectDialog(this);
	if ( ! connectDialog ) return false;

	return true;
}

void MainWindow::buttonSendPressed()
{
	QString text = ui->inputMessage->document()->toPlainText().trimmed();
	text = '[' + getUserNickname() + "] " + text;
	ui->whiteBoard->append(text);
	emit sendMessage(text);
	ui->inputMessage->document()->setPlainText("");
}

