#include "stdafx.h"
#include "reg.h"
#include "util.h"
#include "constants.h"

BOOL IsRegisteredToStartup(PCWSTR pszAppName)
{
	std::wstring vir_app_path;
	GetStringRegKey(autorun_reg_key_name, pszAppName, vir_app_path, L"bad");
	return vir_app_path!=L"bad";
}
BOOL RegisterToStartup(std::wstring path)
{
	return WriteToRegistry(autorun_reg_key_name.c_str(), autorun_reg_value_name.c_str(), (path).c_str(), L"");
}
LONG GetStringRegKey(const std::wstring path, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)
{			
	HKEY hKey;
	LONG lRes = RegOpenKeyExW(HKEY_CURRENT_USER, path.c_str(), 0, KEY_READ, &hKey);

	strValue = strDefaultValue;
	WCHAR szBuffer[512];
	DWORD dwBufferSize = sizeof(szBuffer);
	ULONG nError;
	nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
	if (ERROR_SUCCESS == nError)
	{
		strValue = szBuffer;
		RegCloseKey(hKey);
	}
	return nError;
}
bool DeleteValueKey(HKEY hKeyRoot, std::wstring Subkey, std::wstring ValueKey)
{
	HKEY    hKey        = NULL;
	bool    bReturn     = false;

	if (RegOpenKeyEx(hKeyRoot, Subkey.c_str(), 0, KEY_SET_VALUE , &hKey) == ERROR_SUCCESS)
	{                   
		RegDeleteValue(hKey, ValueKey.c_str() );
		bReturn = true;
	}

	if(hKey != NULL){RegCloseKey(hKey);}

	return bReturn;
}

BOOL WriteToRegistry(PCWSTR subkey, PCWSTR pszAppName, PCWSTR pathToExe, PCWSTR args)
{
	HKEY hKey = NULL;
	LONG lResult = 0;
	BOOL fSuccess = TRUE;
	DWORD dwSize;

	const size_t count = MAX_PATH*12;
	wchar_t szValue[count] = {};


	wcscat_s(szValue, count, pathToExe);

	if (args != NULL)
	{
		wcscat_s(szValue, count, args);
	}

	lResult = RegCreateKeyExW(HKEY_CURRENT_USER, subkey, 0, NULL, 0, (KEY_WRITE | KEY_READ), NULL, &hKey, NULL);

	fSuccess = (lResult == 0);

	if (fSuccess)
	{
		dwSize = (wcslen(szValue)+1)*2;
		lResult = RegSetValueEx(hKey, pszAppName, 0, REG_SZ, (BYTE*)szValue, dwSize);
		fSuccess = (lResult == 0);
	}

	if (hKey != NULL)
	{
		RegCloseKey(hKey);
		hKey = NULL;
	}

	return fSuccess;
}
