///////////////////////////////////////////////////////////////////////////////
//  LMsg.cpp

#include <stdio.h>
#include <stdarg.h>
#include <algorithm>
#include <string>
#include "../../Independent/FormatString/LFormat.h"

#ifdef WIN32
#include <windows.h>
#elif defined(__EMSCRIPTEN__)
#include <emscripten.h>
#endif

#include "LMsg.h"

namespace debug {

HWND__*		g_WindowHandle	= NULL;

bool __cdecl Error(const char* pszFormat, ...)
{
	char szBuf[16384] = "";

	va_list	pArgPtr;

	va_start(pArgPtr, pszFormat);

#ifdef WIN32
	vsprintf_s(szBuf, 16384, pszFormat, pArgPtr);
#else
	vsprintf(szBuf, pszFormat, pArgPtr);
#endif

	va_end(pArgPtr);

#ifdef WIN32
	MessageBox(g_WindowHandle, szBuf, "MocuMocuVRM", MB_OK | MB_SETFOREGROUND | MB_TOPMOST);
#endif

	return false;
}

void __cdecl Output(const char* pszFormat, ...)
{
	char szBuf[16384] = "";

	va_list	pArgPtr;

	va_start(pArgPtr, pszFormat);

#ifdef WIN32
	vsprintf_s(szBuf, 16384, pszFormat, pArgPtr);
#else
	vsprintf(szBuf, pszFormat, pArgPtr);
#endif

	va_end(pArgPtr);

#ifdef WIN32
	OutputDebugString(szBuf);
#elif defined(__EMSCRIPTEN__)
	printf("%s", szBuf);

	std::string Output = szBuf;

	std::string::size_type Pos = 0;

	for (;;) {
		Pos = Output.find("\n", Pos);
		if (Pos == std::string::npos) break;

		Output.replace(Pos, 1, "<br>");
		Pos += 4;
	}

	emscripten_run_script(LFormat::Make(
		"Module.addlog('%s');", Output.c_str()).c_str());
#else
	printf(szBuf);
#endif
}

void SetHWND(HWND__* hWnd)
{
	g_WindowHandle = hWnd;
}

}

