
#include <QtCore/QCoreApplication>
#include <QtCore/QDate>
#include "webservercontrol.h"
#include "mysingalthreadtimer.h"
#include "qsettings.h"
#include <httpserver/httplistener.h>
#include "requesthandler.h"
#include "platformthread.h"
#include <QDir>



QString searchConfigFile()
{
	QString binDir=QCoreApplication::applicationDirPath();
	QString appName=QCoreApplication::applicationName();
	QString fileName("Demo1.ini");

	QStringList searchList;
	searchList.append(binDir);
	searchList.append(binDir+"/etc");
	searchList.append(binDir+"/../etc");
	searchList.append(binDir+"/../../etc");
	searchList.append(binDir+"/../"+appName+"/etc");
	searchList.append(binDir+"/../../"+appName+"/etc");
	searchList.append(QDir::rootPath()+"etc/opt");
	searchList.append(QDir::rootPath()+"etc");

	foreach (QString dir, searchList)
	{
		QFile file(dir+"/"+fileName);
		if (file.exists())
		{
			fileName=QDir(file.fileName()).canonicalPath();
			qDebug("Using config file %s",qPrintable(fileName));
			return fileName;
		}
	}

	// not found
	foreach (QString dir, searchList)
	{
		qWarning("%s/%s not found",qPrintable(dir),qPrintable(fileName));
	}
	qFatal("Cannot find config file %s",qPrintable(fileName));
	return nullptr;
}


int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	 QString configFileName=searchConfigFile();
	 QSettings* listenerSettings=new QSettings(configFileName,QSettings::IniFormat,&a);
	 listenerSettings->beginGroup("listener");

	// Configure and start the TCP listener    
	new HttpListener(listenerSettings,new RequestHandler(&a),&a);

	WebServerControl::GetInstance()->InitQWebSocketServer(6789);
	MySingalThreadTimer::GetInstance()->InitTimerObjects();
	PlatformThread threadrun;
	threadrun.start(QThread::HighestPriority);
	return a.exec();
}
