#include "stdafx.h"
#include "FormMain.h"
#include <QApplication>
#include <QTextCodec>

#include <locale.h>

#include <Qt5Utility/LanguageLoader.h>
using namespace qut;

#include <Qt5SingleAppLib/QtSingleApplication.h>

#include "QSingleAppServer.h"



int SendFileToExist(QtSingleApplication& app, int argc, char *argv[])
{
	for (int i = 1; i < argc; ++i)
	{
		QString msg = QString::fromLocal8Bit(argv[i]);
		app.sendMessage(msg);
	}

	return 0;
}

void LoadQtTranslator(QtSingleApplication& app, QTranslator& translator)
{
	if (LanguageLoader::LoadFromStartupDir(translator))
	{
		app.installTranslator(&translator);
	}
}

void LoadAppTranslator(QtSingleApplication& app, QTranslator& translator)
{
	QString d = QApplication::applicationDirPath();
	d += "/";
	d += "translations/qtgeoviewer_ja.qm";

	if (!translator.load(d))
		return;

	app.installTranslator(&translator);
}

int StartMainForm(QtSingleApplication& app)
{
	QTranslator translator_qt;
	QTranslator translator_app;
	LoadQtTranslator(app, translator_qt);
	LoadAppTranslator(app, translator_app);

	FormMain w;

	app.setActivationWindow(&w);

	QSingleAppServer app_server(&w);
	QObject::connect(&app, SIGNAL(messageReceived(const QString&)), &app_server, SLOT(handleMessage(const QString&)));

	w.show();
	return app.exec();
}

int main(int argc, char *argv[])
{
	setlocale(LC_ALL,"");
	//QTextCodec::setCodecForTr(QTextCodec::codecForLocale());

	QtSingleApplication app(argc, argv);

	if (argc == 1)
		return StartMainForm(app);

	if (!app.isRunning())
		return StartMainForm(app);

	//bool ShiftDown = QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier);
	bool ShiftDown = ((GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0);

	if (ShiftDown)
		return StartMainForm(app);

	return SendFileToExist(app, argc, argv);
}
