#include <QApplication>
#include <QMessageBox>
#include <QMetaEnum>
#include <QInputDialog>
#include "upload_dialog.h"
#include "SH_server_base.h"
#include "SH_ui_sync.h"
#include "pisysteminfo.h"
#include "piqt.h"
#include <pistreampacker.h>
#include "ccm_SHS_shared.h"


UploadDialog::UploadDialog(QWidget * parent): QDialog(parent), Ui::UploadDialog() {
	setupUi(this);
	id = generateID();
	channel.setID(id);
	timer_pip = startTimer(10);
	CONNECTU_QUEUED(&channel, connected, this, connected, this);
	CONNECTU_QUEUED(&channel, dataReceived, this, receiveEvent, this);
	treeServers->startBroadcast();
}


UploadDialog::~UploadDialog() {
	treeServers->stopBroadcast();
}


void UploadDialog::exec(QByteArray baf_) {
	baf = baf_;
	if (baf.isEmpty()) return;
	QDialog::exec();
}


void UploadDialog::timerEvent(QTimerEvent * e) {
	if (e) {
		if (e->timerId() == timer_pip) {
			maybeCallQueuedEvents();
		}
	}
}


void UploadDialog::setState(QString t) {
	labelState->setText(t);
	QApplication::processEvents();
}


void UploadDialog::connected() {
	if (treeServers->isRequesting()) return;

	bool ok = false;
	QString pass = QInputDialog::getText(this, tr("Upload assembly"), tr("Input admin password:"), QLineEdit::Password, "", &ok);
	if (!ok) {
		setState(tr("Waiting for your click"));
		return;
	}
	QApplication::setOverrideCursor(Qt::WaitCursor);
	PIByteArray ph = passwordHash(Q2PIString(pass));
	QApplication::restoreOverrideCursor();

	//emit tcpConnected();
	PIByteArray ba;
	PacketIdentification p = PacketIdentification::makeLocal(SHServer::RoleAdmin, SHS_NETWORK_VERSION, SHS_UISYNC_VERSION);
	p.admin_password = ph;
	ba = SHNetworkTypes::makeHeader(SHNetworkTypes::Identification);
	ba << p;
	setState(tr("Send identification ..."));
	channel.dataSend(ba);

	ba = SHNetworkTypes::makeHeader(SHNetworkTypes::AdminBAFUpload);
	ba << Q2PIByteArray(baf);
	setState(tr("Send .baf ..."));
	channel.dataSend(ba);
}


void UploadDialog::receiveEvent(PIByteArray data) {
	if (treeServers->isRequesting()) return;
	//piCout << "packetReceived" << data.size();
	PacketHeader hdr = SHNetworkTypes::takeHeader(data);
	if (hdr.type < 0) return;
	//qDebug() << "packet type" << type;
	switch ((SHNetworkTypes::PacketType)hdr.type) {
	case SHNetworkTypes::NetworkVersionMismatch:
		QMessageBox::critical(this, "Upload baf", "Invalid network version");
		break;
	case SHNetworkTypes::AdminBAFOk:
		QMessageBox::information(this, "Upload baf", "Success :-)");
		done(QDialog::Accepted);
		break;
	case SHNetworkTypes::AdminBAFFail:
		QMessageBox::critical(this, "Upload baf", "Something goes wrong :-(");
		break;
	case SHNetworkTypes::AdminPasswordFail:
		QMessageBox::critical(this, "Upload baf", "Invalid admin password");
		break;
	default: break;
	}
	setState(tr("Waiting for your click"));
}


void UploadDialog::on_buttonUpload_clicked() {
	treeServers->selectCurrentServer();
}


void UploadDialog::on_treeServers_serverSelected(PacketServerInfo info) {
	channel.dataStop();
	if (!info.isValid())
		return;
	setState(tr("Connect to server %1 (%2) ...").arg(PI2QString(info.name), PI2QString(info.address.fullAddress())));
	//piCout << "connect to" << addr;
	channel.connectToServer(info.address);
}
