/* GMM (C) 2018 Stephane Charette <stephanecharette@gmail.com>
 * $Id: Misc.cpp 2601 2018-09-15 20:40:24Z stephane $
 */

#include "Misc.hpp"

#ifdef WIN32
#include <Windows.h>
#endif


std::string descriptive_username(void)
{
	return	SystemStats::getLogonName	().toStdString() + "@" +
			SystemStats::getComputerName().toStdString();
}


std::string get_url( const std::string &url )
{
	File				output		= File::createTempFile( "gmm.out" );
	const std::string	filename	= output.getFullPathName().toStdString();
	const std::string	user_agent	= "GMM/" GMM_VERSION " (www.ccoderun.ca stephanecharette@gmail.com)";

	const std::string cmd =
		std::string("curl")					+ " "
		"--silent"							+ " "
		"--max-time 60"						+ " "
		"--connect-timeout 10"				+ " "
		"--location-trusted"				+ " "
		"--insecure"						+ " "
		"--user-agent \""	+ user_agent	+ "\" "
		"--output \""		+ filename		+ "\" "
		"--url \""			+ url			+ "\" ";

	LOG_MSG( "external command: " << cmd );

	#ifdef WIN32

	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	memset(&si, '\0', sizeof(si));
	memset(&pi, '\0', sizeof(pi));

	SetLastError( 0 );
	BOOL success = CreateProcess(
		NULL,				// title
		LPSTR(cmd.c_str()),	// command
		NULL,				// process attributes
		NULL,				// thread attributes
		FALSE,				// inherit handles
		CREATE_NO_WINDOW,	// do not create a window for the process (hidden!)
		NULL,				// environment
		NULL,				// current directory
		&si,				// startup info
		&pi );				// process info

	DWORD rc = GetLastError();
	if (rc)
	{
		char *msg = nullptr;
		FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER	|
			FORMAT_MESSAGE_FROM_SYSTEM		|
			FORMAT_MESSAGE_IGNORE_INSERTS	,
			NULL							,
			rc								,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			(LPSTR)&msg,
			0,
			NULL);

		LOG_MSG( "curl: received error #" << rc << ": " << msg );
		LocalFree( msg );
	}

	if (success)
	{
		WaitForSingleObject(pi.hProcess, INFINITE);
		GetExitCodeProcess(pi.hProcess, &rc);
	}
	CloseHandle( pi.hProcess );
	CloseHandle( pi.hThread );

	#else
	const int rc = system( cmd.c_str() );
	#endif

	std::string txt;

	if (rc)
	{
		LOG_MSG( "rc=" << rc << " when running: " << cmd );
	}

	txt = Lox::readFile( filename );
	output.deleteFile();

	return txt;
}

