// ConfigMgr.cpp: implementation of the CProfile class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ConfigMgr.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CProfile::CProfile(LPCTSTR filename)
{
    CString str;

    ::GetModuleFileName(_Module.GetModuleInstance()
                       , str.GetBufferSetLength(MAX_PATH)
                       , MAX_PATH * sizeof(TCHAR));
    m_strPath = str.Left(str.ReverseFind(_T('\\')) + 1) + filename;

    DWORD attribs = ::GetFileAttributes(m_strPath);
    if (attribs & FILE_ATTRIBUTE_READONLY)
    {
        if (::SetFileAttributes(m_strPath, attribs |= ~FILE_ATTRIBUTE_READONLY))
        {
            // cannot change file attributes. CDROM?
            ::GetTempPath(MAX_PATH * sizeof(TCHAR), str.GetBufferSetLength(MAX_PATH));
            str += filename;
            if (::CopyFile(m_strPath, str, FALSE))
            {
                m_strPath = str;
            }
        }
    }
}

CProfile::~CProfile() {}

// Accessors / modifiers

HRESULT CProfile::QueryValue(int& value, LPCTSTR pValueName)
{
    TCHAR data[16];

    ::GetPrivateProfileString(m_strSection, pValueName, _T("0")
                             , data, sizeof(data), m_strPath);
    value = strtol(data, 0, 0);

    return S_OK;
}

HRESULT CProfile::QueryValue(float& value, LPCTSTR pValueName)
{
    TCHAR data[16];

    ::GetPrivateProfileString(m_strSection, pValueName, _T("0")
                             , data, sizeof(data), m_strPath);
    value = (float)atof(data);

    return S_OK;
}

HRESULT CProfile::QueryValue(LPTSTR szValue, LPCTSTR pValueName, LPDWORD pcb)
{
    *pcb = ::GetPrivateProfileString(m_strSection, pValueName, _T("")
                                    , szValue, *pcb, m_strPath);
    return S_OK;
}

HRESULT CProfile::SetValue(int value, LPCTSTR pValueName)
{
    TCHAR data[16];

    sprintf(data, "%d", value);
    BOOL ret = ::WritePrivateProfileString(m_strSection, pValueName
                                          , data, m_strPath);

    return (ret)? S_OK : E_FAIL;
}

HRESULT CProfile::SetValue(float value, LPCTSTR pValueName)
{
    TCHAR data[16];

    sprintf(data, "%10.5f", value);
    BOOL ret = ::WritePrivateProfileString(m_strSection, pValueName
                                          , data, m_strPath);

    return (ret)? S_OK : E_FAIL;
}

HRESULT CProfile::SetValue(LPCTSTR pszValue, LPCTSTR pValueName)
{
    BOOL ret = ::WritePrivateProfileString(m_strSection, pValueName
                                          , pszValue, m_strPath);

    return (ret)? S_OK : E_FAIL;
}

HRESULT CProfile::Open(LPCTSTR pSectionName)
{
    m_strSection = pSectionName;
    
    return S_OK;
}

HRESULT CProfile::Close()
{
    m_strSection.Empty();

    return S_OK;
}
