#include"jltest.h"

#include<qpushbutton.h>
#include<qlayout.h>
#include<qcheckbox.h>
#include<qmessagebox.h>
#include<qgroupbox.h>
#include<qprogressbar.h>
#include<qradiobutton.h>
#include<qbuttongroup.h>
#include<qdom.h>
#include<qtimer.h>
#include<stdlib.h>
#include"im.h"
#include"xmpp_jidlink.h"
#include"xmpp_xmlcommon.h"
#include"psiaccount.h"
#include"busywidget.h"

#define TOTAL_SIZE   32768
#define PACKET_SIZE  8192
#define PACKET_DELAY 2000

class JLTestDlg::Private
{
public:
	PsiAccount *pa;
	Jid jid;
	BusyWidget *busy;
	QRadioButton *rb_dtcp, *rb_ibb;
	QPushButton *pb_test;
	QProgressBar *pr_status;
	QButtonGroup *bg_type;
	JidLink *jl;
	QLabel *lb_status;
	int mode;

	int numBytes;
};

JLTestDlg::JLTestDlg(const Jid &j, PsiAccount *pa)
:QDialog(0, 0, false, WDestructiveClose)
{
	d = new Private;
	d->pa = pa;
	d->jid = j;
	d->mode = ModeConnect;
	d->jl = 0;
	setCaption("Link Test");
	init();
	d->pb_test->setText(tr("Connect"));

	d->rb_dtcp->setChecked(true);
}

JLTestDlg::JLTestDlg(const Jid &j, JidLink *jl, PsiAccount *pa)
:QDialog(0, 0, false, WDestructiveClose)
{
	d = new Private;
	d->pa = pa;
	d->jid = j;
	d->mode = ModeAccept;
	d->jl = jl;
	setCaption("Link Test");
	init();
	d->pb_test->setText(tr("Accept"));
	if(jl->type() == JidLink::DTCP)
		d->rb_dtcp->setChecked(true);
	else
		d->rb_ibb->setChecked(true);
	d->bg_type->setEnabled(false);
}

void JLTestDlg::init()
{
	QVBoxLayout *vb = new QVBoxLayout(this, 8);

	// JID
	QLabel *l = new QLabel(QString("Link test with %1").arg(d->jid.full()), this);
	vb->addWidget(l);

	// type selection
	d->bg_type = new QButtonGroup(1, Vertical, "Type", this);
	vb->addWidget(d->bg_type);
	d->rb_dtcp = new QRadioButton("Direct (S5B)", d->bg_type);
	d->rb_ibb = new QRadioButton("Thru-server (IBB)", d->bg_type);

	// status area
	QGroupBox *gr = new QGroupBox(1, Horizontal, "Status", this);
	d->pr_status = new QProgressBar(100, gr);
	d->pr_status->setProgress(0);
	d->lb_status = new QLabel(gr);
	d->lb_status->setText("Idle");

	vb->addWidget(gr);

	vb->addStretch(1);
	QHBoxLayout *hb = new QHBoxLayout(vb);
	d->busy = new BusyWidget(this);
	hb->addWidget(d->busy);
	d->pb_test = new QPushButton(this);
	connect(d->pb_test, SIGNAL(clicked()), SLOT(start()));
	hb->addWidget(d->pb_test);
	QPushButton *pb_close = new QPushButton(tr("Close"), this);
	connect(pb_close, SIGNAL(clicked()), SLOT(close()));
	hb->addWidget(pb_close);

	d->pb_test->setFocus();
}

JLTestDlg::~JLTestDlg()
{
	if(d->jl) {
		d->jl->close();
		delete d->jl;
	}
	delete d;
}

void JLTestDlg::reset()
{
	d->mode = ModeConnect;
	d->pb_test->setEnabled(true);
	d->pb_test->setText(tr("Connect"));
	d->lb_status->setText("Idle");
	d->pr_status->setProgress(0);
	d->bg_type->setEnabled(true);
}

void JLTestDlg::start()
{
	if(d->mode == ModeConnect) {
		int type;
		if(d->rb_dtcp->isChecked())
			type = JidLink::DTCP;
		else
			type = JidLink::IBB;

		d->jl = new JidLink(d->pa->client());
		connect(d->jl, SIGNAL(connected()), SLOT(jl_connected()));
		connect(d->jl, SIGNAL(connectionClosed()), SLOT(jl_connectionClosed()));
		connect(d->jl, SIGNAL(error(int)), SLOT(jl_error(int)));
		connect(d->jl, SIGNAL(bytesWritten(int)), SLOT(jl_bytesWritten(int)));
		connect(d->jl, SIGNAL(readyRead()), SLOT(jl_readyRead()));

		QDomElement e = textTag(d->pa->client()->doc(), "comment", "this is only a test!");
		d->jl->connectToJid(d->jid, type, e);

		d->bg_type->setEnabled(false);
		d->lb_status->setText("Requesting...");
	}
	else {
		connect(d->jl, SIGNAL(connected()), SLOT(jl_connected()));
		connect(d->jl, SIGNAL(connectionClosed()), SLOT(jl_connectionClosed()));
		connect(d->jl, SIGNAL(error(int)), SLOT(jl_error(int)));
		connect(d->jl, SIGNAL(bytesWritten(int)), SLOT(jl_bytesWritten(int)));
		connect(d->jl, SIGNAL(readyRead()), SLOT(jl_readyRead()));

		d->jl->accept();

		d->lb_status->setText("Connecting...");
	}

	d->busy->start();
	d->pb_test->setEnabled(false);
}

void JLTestDlg::jl_connected()
{
	d->lb_status->setText("Transferring data...");
	d->numBytes = 0;

	if(d->mode == ModeConnect)
		doNext();
}

void JLTestDlg::jl_connectionClosed()
{
	d->busy->stop();

	delete d->jl;
	d->jl = 0;

	QMessageBox::information(this, tr("Error"), tr("Connection closed."));

	reset();
}

void JLTestDlg::jl_error(int)
{
	d->busy->stop();

	QString str;
	delete d->jl;
	d->jl = 0;

	/*if(x == DTCPConnection::ErrRequest)
		str = tr("Error during request!");
	else if(x == DTCPConnection::ErrConnect)
		str = tr("Error during connect!");
	else
		str = tr("Socket error!");*/
	str = tr("Stream or connection error.");

	QMessageBox::information(this, tr("Error"), str);

	reset();
}

void JLTestDlg::jl_readyRead()
{
	QByteArray r;
	r = d->jl->read();
	printf("got [%d] bytes\n", r.size());

	d->numBytes += r.size();
	int percent = 100 * d->numBytes / TOTAL_SIZE;
	d->pr_status->setProgress(percent);

	if(d->numBytes >= TOTAL_SIZE) {
		d->busy->stop();

		d->jl->close();
		delete d->jl;
		d->jl = 0;

		d->lb_status->setText("Finished");
	}
}

void JLTestDlg::jl_bytesWritten(int x)
{
	d->numBytes += x;
	int percent = 100 * d->numBytes / TOTAL_SIZE;
	d->pr_status->setProgress(percent);

	if(d->jl->bytesToWrite() > 0)
		return;

	if(d->numBytes >= TOTAL_SIZE) {
		d->busy->stop();

		d->jl->close();
		d->jl->deleteLater();
		d->jl = 0;

		d->lb_status->setText("Finished");
	}
	else {
		QTimer::singleShot(PACKET_DELAY, this, SLOT(doNext()));
	}
}

void JLTestDlg::doNext()
{
	if(!d->jl)
		return;

	writePacket();
}

void JLTestDlg::writePacket()
{
	QByteArray a(PACKET_SIZE);
	for(int n = 0; n < (int)a.size(); ++n)
		a[n] = rand();
	d->jl->write(a);
}
