#include "stdafx.h"
#include "PluginArgs.h"
#include "QEnv.h"

#include <QDir>


namespace qut
{


PluginArgs::PluginArgs(int argc, char *argv[])
{
	InitStdArgumentsCopy(argc, argv);

	if (!IsExistLocalCopy(argv))
		AddReferenceToSDK();
}

int& PluginArgs::GetArgc(void)
{
	return argc_ext;
}

char** PluginArgs::GetArgv(void)
{
	return &arg_ext[0];
}

void PluginArgs::InitStdArgumentsCopy(int argc, char *argv[])
{
	argc_ext = argc;
	arg_ext.reserve(argc_ext);
	for (int i = 0; i < argc; ++i)
	{
		arg_ext.push_back(argv[i]);
	}
}

bool PluginArgs::IsExistLocalCopy(char *argv[])
{
	QString dir = GetStartupPath(argv);
		
	if (QFile(dir + "\\" "Qt5Core.dll").exists())
		return true;
	if (QFile(dir + "\\" "Qt5Cored.dll").exists())
		return true;

	return false;
}

QString PluginArgs::GetStartupPath(char *argv[])
{
	QString cmd = QString::fromLocal8Bit(argv[0]);
	QString d = QFileInfo(cmd).dir().path();
	return QDir::toNativeSeparators(d);
}

QString PluginArgs::GetPluginDirFromEnv(void)
{
	QString sdk_dir = QEnv::GetEnvParam("QTDIR");
	if (sdk_dir.isEmpty())
		return QString("");

	return sdk_dir + QString("\\plugins");
}

void PluginArgs::AddReferenceToSDK(void)
{
	plugin_opt = "-platformpluginpath";
	plugin_path = GetPluginDirFromEnv().toLocal8Bit();

	if (!plugin_path.empty())
	{
		arg_ext.push_back(&plugin_opt[0]);
		arg_ext.push_back(&plugin_path[0]);
		argc_ext += 2;
	}
}


}
