#include "FontAtlasBuilder.h"

#include "NativeHandles.h"

#include <string>
#include <windows.h>

namespace RenderCadenceCompositor
{
namespace
{
std::string LastWindowsErrorText()
{
	const DWORD errorCode = GetLastError();
	return std::to_string(static_cast<unsigned long>(errorCode));
}
}

bool FontAtlasBuilder::RunProcess(const std::string& commandLine, const std::filesystem::path& workingDirectory, std::string& error)
{
	STARTUPINFOA startupInfo = {};
	PROCESS_INFORMATION processInfo = {};
	startupInfo.cb = sizeof(startupInfo);

	std::vector<char> mutableCommandLine(commandLine.begin(), commandLine.end());
	mutableCommandLine.push_back('\0');

	if (!CreateProcessA(nullptr, mutableCommandLine.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, workingDirectory.string().c_str(), &startupInfo, &processInfo))
	{
		error = "Failed to launch msdf-atlas-gen.exe. Windows error: " + LastWindowsErrorText() + ".";
		return false;
	}

	UniqueHandle processHandle(processInfo.hProcess);
	UniqueHandle threadHandle(processInfo.hThread);
	WaitForSingleObject(processHandle.get(), INFINITE);

	DWORD exitCode = 0;
	GetExitCodeProcess(processHandle.get(), &exitCode);
	if (exitCode != 0)
	{
		error = "msdf-atlas-gen.exe returned a non-zero exit code: " + std::to_string(static_cast<unsigned long>(exitCode)) + ".";
		return false;
	}

	error.clear();
	return true;
}
}
