#include "mainwindow.h"
#include <QApplication>
#include "loginwindow.h"
#include "InputObject.h"
#include <QQmlApplicationEngine>
#include "db/SQLHelper.h"
#include <QTextCodec>
#include <QFontDatabase>
#include <QDebug>
#include <QThread>
#include <QTimer>
#include "log/UserOperationLog.h"
#include <QTranslator>
#include <src/device/DeviceManager.h>
#include "json/jsonobject.h"
#include "locker.h"
#include "languageswitcher.h"
QString loadFontFromFile(QString path)
{
	static QString font;
	static  bool loaded = false;
	if (!loaded)
	{
		loaded = true;
		int loadedFontID = QFontDatabase::addApplicationFont(path);
		QStringList loadedFontFamilies = QFontDatabase::applicationFontFamilies(loadedFontID);
		if (!loadedFontFamilies.empty())
			font = loadedFontFamilies.at(0);
	}
	return font;
}

int main(int argc, char* argv[])
{
	//QLocale::setDefault(QLocale::English);
	qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
#ifdef CUTE_STYLE
	qputenv("QT_VIRTUALKEYBOARD_STYLE", QByteArray("retro"));
#endif // CUTE_STYLE

	//qputenv("QT_LOGGING_RULES", QByteArray("qt.virtualkeyboard=true"));


	QApplication a(argc, argv);
	QString layouts_path = QString(QCoreApplication::applicationDirPath()).append("/layouts");
	qputenv("QT_VIRTUALKEYBOARD_LAYOUT_PATH", QByteArray(layouts_path.toStdString().c_str()));

	QTextCodec* codec = QTextCodec::codecForName("utf8");
	QTextCodec::setCodecForLocale(codec);


	//multi-language suppport
	QTranslator translator;
	LanguageSwitcher::Instance()->setTranslator(&translator);
	LanguageSwitcher::Instance()->setDefaultLanguage(JsonObject::Instance()->defaultLanguage());
	a.installTranslator(&translator);


	//QString fontName = loadFontFromFile(":/fonts/MicrosoftYahei.ttf");
	QString fontName = loadFontFromFile(":/fonts/DroidSansFallback.ttf");
	QFont font(fontName);
	QApplication::setFont(font);

	InputObject* obj = new InputObject();
	a.installEventFilter(obj);
	SQLHelper::Open();
	MainWindow w;
	UserOperationLog::Default()->init();

	//暂时为了调试关闭锁屏
	//Locker::Instance()->start();
	//QObject::connect(obj, SIGNAL(touchScreen()), Locker::Instance(), SLOT(refreshTimer()));
	QList<Qt::GestureType> gestures;
	gestures << Qt::SwipeGesture;
	gestures << Qt::PanGesture;
	w.grabGestures(gestures);

	QStringList app_args = a.arguments();
	int ret = 0;

	if (app_args.contains("-d"))
		//if (true)
	{

		w.debugConsoleOn();
		w.showFullScreen();

		qInstallMessageHandler(MainWindow::QMessageOutput);
		QThread thread;
		StdOutRedirector redir;
		redir.setOutputTF(w.getEdit());
		QTimer Timer;
		redir.moveToThread(&thread);
		QObject::connect(&Timer, SIGNAL(timeout()), &redir, SLOT(readOutsToTF()));
		fflush(stdout);
		Timer.start(1000);
		thread.start();


		DeviceManager::Default()->initDevice();
		w.requestLogin();

		ret = a.exec();
		thread.terminate();

	}
	else {
		w.showFullScreen();
		DeviceManager::Default()->initDevice();
		w.requestLogin();
		ret = a.exec();
	}
	DeviceManager::Default()->close();
	return ret;
}
