#include "pch.h"
#include "Internal.h"

using namespace TwitchInGames;

namespace {
	char const* const sdkPlatform= PLATFORM;
#ifdef UNITY
	char const* const sdkRuntime= "Unity";
#else
	char const* const sdkRuntime= "C++";
#endif
	tstring nullGuid= _T("00000000-0000-0000-0000-000000000000");

#define ReturnIfError(result) do { if((result) != ERROR_SUCCESS) return tstring(); } while(false)

	tstring GetApplicationName() {
		auto* commandLine= GetCommandLine();
		if(commandLine[0] == _T('"')) {
			++commandLine;
			auto* quote= _tcschr(commandLine, _T('"'));
			if(quote != nullptr) {
				*quote= _T('\0');
			}
		} else {
			auto* space= _tcschr(commandLine, _T(' '));
			if(space != nullptr) {
				*space= _T('\0');
			}
		}
		auto const* separator= _tcsrchr(commandLine, _T('\\'));
		if(separator != nullptr) {
			return tstring(separator + 1);
		}
		return commandLine;
	}

	tstring GetDeviceId() {
		auto const* keyName = _T("SOFTWARE\\Microsoft\\Cryptography");
		auto const* valueName = _T("MachineGuid");
		RegKey key;
		auto result= RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_READ, &key);
		if(result == ERROR_ACCESS_DENIED) {
			result= RegOpenKeyEx(HKEY_CURRENT_USER, keyName, 0, KEY_READ, &key);
		}
		ReturnIfError(result);
		DWORD type, n= 0;
		result= RegQueryValueEx(key, valueName, nullptr, &type, nullptr, &n);
		ReturnIfError(result);
		tstring deviceId(n / sizeof(tstring::value_type), _T('\0'));
		result= RegQueryValueEx(key, valueName, nullptr, &type, reinterpret_cast<LPBYTE>(&deviceId[0]), &n);
		ReturnIfError(result);
		if(deviceId != nullGuid) {
			_tcslwr_s(&deviceId[0], deviceId.size());
			deviceId.pop_back();
		} else {
			deviceId.clear();
		}
		return deviceId;
	}
}

#include "Analytics.inl"
