#include "StdAfx.h"
#include "Settings.h"
#include "BKDE.h"

/*
Код стыренный из BKBTL. Потому что лень самому изобретать.
*/

CSettings::CSettings(void)
{
	m_Settings_RegKey = (HKEY) INVALID_HANDLE_VALUE;
	m_Settings_RegKeyName = _T("Software\\") + CString(theApp.m_pszRegistryKey) + _T("\\") +
	                        CString(theApp.m_pszProfileName);
}

CSettings::~CSettings(void)
{
}

void CSettings::Settings_Init()
{
	LONG lResult = ::RegOpenKeyEx(HKEY_CURRENT_USER, m_Settings_RegKeyName, 0, KEY_ALL_ACCESS, &m_Settings_RegKey);

	if (lResult != ERROR_SUCCESS)
	{
		lResult = ::RegCreateKeyEx(HKEY_CURRENT_USER, m_Settings_RegKeyName, 0, NULL, 0, KEY_ALL_ACCESS,
		                           NULL, &m_Settings_RegKey, NULL);
	}
}

void CSettings::Settings_Done()
{
	::RegCloseKey(m_Settings_RegKey);
}

BOOL CSettings::Settings_SaveStringValue(LPCTSTR sName, LPCTSTR sValue)
{
	LONG lResult;

	if (sValue == NULL)
	{
		lResult = ::RegSetValueEx(m_Settings_RegKey, sName, 0, REG_SZ, (const BYTE *) L"", sizeof(TCHAR));
	}
	else
		lResult = ::RegSetValueEx(m_Settings_RegKey, sName, 0, REG_SZ, (const BYTE *) sValue,
		                          (lstrlen(sValue) + 1) * sizeof(TCHAR));

	return (lResult == ERROR_SUCCESS);
}

BOOL CSettings::Settings_LoadStringValue(LPCTSTR sName, LPTSTR sBuffer, int nBufferLengthChars)
{
	if (sBuffer == NULL)
	{
		return FALSE;
	}

	DWORD dwType;
	DWORD dwBufLength = nBufferLengthChars * sizeof(TCHAR);
	LONG lResult = ::RegQueryValueEx(m_Settings_RegKey, sName, NULL, &dwType, (LPBYTE) sBuffer, &dwBufLength);

	if (lResult == ERROR_SUCCESS && dwType == REG_SZ)
	{
		return TRUE;
	}
	else
	{
		sBuffer[0] = 0;
		return FALSE;
	}
}
