#include <iostream>

#include "Util.h"
#include "pathcch.h"

bool isError(const HRESULT result, const std::stringstream message)
{
	if (FAILED(result))
	{
		std::cout << message.str() << std::hex << result << std::endl;
		return true;
	}
	return false;
}

bool isError(const HRESULT result, const char* message)
{
	return isError(result, std::stringstream(message));
}

std::string utf8Encode(const std::wstring& wstr)
{
	if (wstr.empty())
	{
		return std::string();
	}

	int sizeNeeded = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
	std::string resultString(sizeNeeded, 0);
	WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &resultString[0], sizeNeeded, NULL, NULL);
	return resultString;
}

HRESULT getAppPath(std::wstring& outPath)
{
	const size_t MAX_PATH_LENGTH = 32767;
	outPath.resize(MAX_PATH_LENGTH);
	HRESULT hr = GetModuleFileName(NULL, &outPath[0], static_cast<DWORD>(outPath.size()));
	if (isError(hr, "Failed to get executable name: ")) return hr;
	outPath.resize(wcslen(outPath.data()));
	return hr;
}

HRESULT getAppDir(std::wstring& outPath)
{
	HRESULT hr = getAppPath(outPath);
	if (FAILED(hr)) return hr;

	hr = PathCchRemoveFileSpec(&outPath[0], static_cast<DWORD>(outPath.size()));
	if (isError(hr, "Failed to get executable dir: ")) return hr;
	outPath.resize(wcslen(outPath.data()));
	return hr;
}