/*
    Copyright (C) 2015 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    MA 02110-1301  USA.
*/

#include "webserverprocess.h"
#include "moc_webserverprocess.cpp"

#include "sitestingconfig.h"

#include <QTcpSocket>
#include <QRegExp>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QTime>
#include <QCoreApplication>
#include <QTest>
#include <QDir>

WebserverProcess::WebserverProcess(QObject* parent)
 : QObject(parent)
{
	_process = new QProcess(this);
	connect(_process, SIGNAL(error(QProcess::ProcessError)),
					this, SLOT(processError(QProcess::ProcessError)));
	connect(_process, SIGNAL(finished(int,QProcess::ExitStatus)),
					this, SLOT(processFinished(int,QProcess::ExitStatus)));
	connect(_process, SIGNAL(readyRead()),
					this, SLOT(processReadyRead()));
}

WebserverProcess::~WebserverProcess()
{
	if(_process && _process->state() == QProcess::Running){
		_process->kill();
		_process->waitForFinished(5000);
	}
	cleanupDataDirectory();
}

QString WebserverProcess::webserviceBaseUrl()
{
	return appendSlashToUrl(QString(WEBSERVICE_BASE_URL));
}

QString WebserverProcess::webserviceApiVersion()
{
	return QString(WEBSERVICE_API_VERSION);
}


bool WebserverProcess::isRunning() const
{
	if(!_process)
		return false;

	QRegExp regex("http:\\/\\/([^:]+)+:([0-9]+)");
	if(regex.indexIn(webserviceBaseUrl()) < 0){
		qDebug() << QString("Regex %1 to find host and port not matching in %2").arg(regex.pattern()).arg(webserviceBaseUrl());
		return false;
	}
	QStringList capturedTexts = regex.capturedTexts();
	if(capturedTexts.size() != 3){
		qDebug() << QString("Regex %1 does not matches enough items in %2").arg(regex.pattern()).arg(webserviceBaseUrl());
		return false;
	}
	QTcpSocket *socket = new QTcpSocket();
	socket->connectToHost(capturedTexts[1], capturedTexts[2].toInt(), QIODevice::ReadOnly); 
	if (!socket->waitForConnected()){
		qDebug() << QString("Webservice at %1:%2 not reachable").arg(capturedTexts[1]).arg(capturedTexts[2]);
		delete socket;
		return false;
	}
	socket->close();
	delete socket;
	return true;
}

bool WebserverProcess::start()
{
	if(!_process)
		return false;

	QStringList arguments;
	arguments << QString("-S %1:%2").arg(QString(WEBSERVICE_SERVER_HOST)).arg(QString(WEBSERVICE_SERVER_PORT));
	arguments << QString("-t %1").arg(QString(WEBSERVICE_SERVER_DOCROOT));
	
	connect(_process, SIGNAL(error(QProcess::ProcessError)),
					this, SLOT(processError(QProcess::ProcessError)));
	connect(_process, SIGNAL(finished(int,QProcess::ExitStatus)),
					this, SLOT(processFinished(int,QProcess::ExitStatus)));
	connect(_process, SIGNAL(readyRead()),
					this, SLOT(processReadyRead()));
	
 	_process->setReadChannelMode(QProcess::ForwardedChannels);
	_process->start(QString("%1 %2").arg(QString(PHP_EXECUTABLE)).arg(arguments.join(" ")));
	// give the php webserver a few seconds to start
 	QTest::qWait(5000);
 	if(!isRunning())
		return false;
	return true;
}

bool WebserverProcess::stop()
{
	if(!_process)
		return true;
	_process->terminate();
	return _process->waitForFinished(5000);
}


bool WebserverProcess::setup()
{
	if(!_process)
		return false;

	QRegExp regex("http:\\/\\/([^:]+)+:([0-9]+)");
	if(regex.indexIn(webserviceBaseUrl()) < 0){
		qDebug() << QString("Regex %1 to find host and port not matching in %2").arg(regex.pattern()).arg(webserviceBaseUrl());
		return false;
	}
	QStringList capturedTexts = regex.capturedTexts();
	if(capturedTexts.size() != 3){
		qDebug() << QString("Regex %1 does not matches enough items in %2").arg(regex.pattern()).arg(webserviceBaseUrl());
		return false;
	}
	QNetworkAccessManager *manager = new QNetworkAccessManager(this);
	QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(QString("%1%2").arg(webserviceBaseUrl()).arg("index.php/setup"))));
	QTime dieTime = QTime::currentTime().addSecs(30);
	while(QTime::currentTime() < dieTime){
		if(reply->isFinished())
			break;
		QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 100);
	}
	bool result = reply->isFinished();
	reply->deleteLater();
	manager->deleteLater();
	return result;
}

bool WebserverProcess::cleanupDataDirectory()
{
	QDir dir(QString(WEBSERVICE_SERVER_DOCROOT));
	if(!dir.exists())
		return true;
	if(!dir.removeRecursively())
		return false;
	return true;
}

void WebserverProcess::processError(QProcess::ProcessError error)
{
	QString errorString;
	switch(error){
		case QProcess::FailedToStart:
			errorString = "FailedToStart";
			break;
		case QProcess::Crashed:
			errorString = "Crashed";
			break;
		case QProcess::Timedout:
			errorString = "Timedout";
			break;
		case QProcess::WriteError:
			errorString = "WriteError";
			break;
		case QProcess::ReadError:
			errorString = "ReadError";
			break;
		default:
			errorString = "Unknown";
	}

	qDebug() << QString("%1: Error %2 (%3)")
								.arg(metaObject()->className()).arg(errorString).arg(int(error));
}

void WebserverProcess::processFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
	QString exitString;
	switch(exitStatus){
		case QProcess::NormalExit:
			exitString = "NormalExit";
			break;
		case QProcess::CrashExit:
			exitString = "CrashExit";
			break;
		default:
			exitString = "Unknown";
	}
	qDebug() << QString("%1: Finished with exit code %2 and staus %3 (%4)")
								.arg(metaObject()->className()).arg(exitCode).arg(exitString).arg(int(exitStatus));
}

void WebserverProcess::processReadyRead()
{
	QProcess *process = qobject_cast<QProcess*>(sender());
	if(!process)
		return;
	qDebug() << QString("%1: Read %2")
							.arg(metaObject()->className()).arg(QString::fromUtf8(process->readAll()));
}

QString WebserverProcess::appendSlashToUrl(QString url)
{
	if(url.right(1) != "/")
		url += "/";
	return url;
}
