#include "copydialog.h"
//
copydialog::copydialog(QWidget * parent, QString source, QString destination, bool *ok) : QDialog(parent)
{
	setupUi(this);
	sourceFilename = source;
	destinationFilename=destination;
	*ok=true;
	globalOK = ok;
	servernameLabel->setText(sourceFilename);
	filenameLabel->setText(destinationFilename);
	manager = new QNetworkAccessManager(this);
	connect(manager,SIGNAL(finished(QNetworkReply *)),this,SLOT(slot_finished(QNetworkReply *)));
	stream = new QDataStream();
	buffersize = 2097152;
	buffer = new char[buffersize+1];
	time = new QTime();
	headerFound = false;
	blocksRead = 0;
	errorFlag = false;
	redirectFlag = false;
	direction = 0;
	position = 0;
	time->start();
	request.setUrl(sourceFilename);
	reply = manager->get(request);
	statusLabel->setText("Status : Anfrage eingeleitet .....");
	reply->setReadBufferSize(buffersize);
	if (reply == NULL) slot_abortButtonClicked();
	connect(reply,SIGNAL(readyRead()),this,SLOT(slot_readyRead()));
	connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(slot_error(QNetworkReply::NetworkError)));
}

void copydialog::slot_abortButtonClicked(){
	*globalOK = false;
	output.close();
	this->reject();
}

void copydialog::slot_finished(QNetworkReply * data){
	data = data; // just to keep the compiler happy ....
	output.close();
	if (errorFlag) {
		statusLabel->setText("Status : Fehler gefunden .....");
		QFile delFile(destinationFilename);
		delFile.remove();
		*globalOK = false;
		QMessageBox::information(this,"FEHLER",errorMessage);
	}
	if (redirectFlag){
		redirectFlag = false;
		headerFound = false;
		if (output.isOpen()) output.close();
		request.setUrl(redirect);
		statusLabel->setText("Status : Initialisiere Weiterleitungsanfrage .....");
		reply = manager->get(request);
		reply->setReadBufferSize(buffersize);
		connect(reply,SIGNAL(readyRead()),this,SLOT(slot_readyRead()));
		connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(slot_error(QNetworkReply::NetworkError)));
	} else {
		this->accept();	
	}
}

void copydialog::slot_readyRead(){
long int rc = reply->read(buffer,buffersize);
long int elapsed = time->elapsed();
long int transferRate;
long int remaining;
QString statusMessage;

	elapsedTimeLabel->setText(msToString(elapsed));
	transferRate = (rc + blocksRead) / elapsed * 1000;
	transferRate = transferRate / 1000;
	if (!headerFound){
		QVariant header2 = reply->header(QNetworkRequest::LocationHeader);
		if (header2.isValid()){
			statusLabel->setText("Status : Redirect found ......");
			redirect = header2.toUrl();
			redirectFlag = true;
		}
		QVariant header = reply->header(QNetworkRequest::ContentLengthHeader);
		if (header.isValid()){
			statusLabel->setText("Status : Volume Info gefunden");
			headerFound = true;
			fileSizeLabel->setText(valueToString(header.toLongLong()));
			rc2 = system("echo \"Volume Info ausgeben\"");
			progress->setMaximum(header.toLongLong());
			output.setFileName(destinationFilename);
			if (output.open(QIODevice::WriteOnly)){
				stream->setDevice(&output);
			}
		}
	}
	while (rc != 0){
		statusMessage = "Status : Datei wird kopiert. ";
		if (direction == 0){
			if (position < 110){
				position++;
			} else {
				direction = 1;
			}
		} else {
			if (position > 1){
				position--;
			} else {
				direction = 0;
			}
		}
		for (int i=0;i<position;i++) statusMessage = statusMessage + " ";
		statusMessage = statusMessage + "*";
		statusLabel->setText(statusMessage);
		blocksRead+=rc;
		progress->setValue(blocksRead);
		stream->writeRawData((const char *)buffer,rc);
		rc = reply->read(buffer,buffersize);
	}
	transferRateLabel->setText(valueToString(transferRate*1000));
	downloadLabel->setText(valueToString(blocksRead));
	if (transferRate > 0) {
		remaining = (progress->maximum() / transferRate);
		estimateLabel->setText(msToString(remaining));
		remaining = remaining - elapsed + 1000;
		remainingTimeLabel->setText(msToString(remaining));
	} else {
		estimateLabel->setText("n/a");
		remainingTimeLabel->setText("n/a");
	}
}

void copydialog::slot_error(QNetworkReply::NetworkError code){
QString errorString = reply->errorString();
	code = code; // just to keep the compiler happy;
	errorMessage = errorString;
	errorFlag = true;
}

QString copydialog::valueToString(long int value){
QString rc;
long int kilo = 1024;
long int mega = 1048576;
long int giga = 1073741824;
float floatValue;

	if (value > giga) {
		floatValue = (float)value / (float)giga;
		rc.sprintf("%f.3",floatValue);
		if (rc.contains(".")) rc = rc.left(rc.indexOf(".") + 4);
		rc = rc + " GB";
	} else {
		if (value > mega) {
			floatValue = (float)value / (float)mega;
			rc.sprintf("%f.3",floatValue);
			if (rc.contains(".")) rc = rc.left(rc.indexOf(".") + 4);
			rc = rc  + " MB";
		} else {
			if (value > kilo) {
				floatValue = (float)value / (float)kilo;
				rc.sprintf("%f.3",floatValue);
				if (rc.contains(".")) rc = rc.left(rc.indexOf(".") + 4);
				rc = rc + " KB";
			} else {
				rc = QString::number(value) + " B";
			}
		}
	}
	return rc;
}

QString copydialog::msToString(long int value){
long int hour;
long int min;
QString rc;

	value = value / 1000; 
	hour = value / 3600;
	hour < 10?rc = "0" + QString::number(hour):rc = QString::number(hour);
	value = value - hour * 3600;
	min = value / 60;
	min < 10?rc = rc + ":0" + QString::number(min):rc = rc + ":" + QString::number(min);
	value = value - min * 60;
	value < 10?rc = rc + ":0" + QString::number(value):rc = rc + ":" + QString::number(value);
	return rc;
}
//

