// SettingOptionPage.cpp : 구현 파일입니다.
//

#include "stdafx.h"
#include "PMSetting.h"

CPMSetting::CPMSetting()
:   m_szSetupFileName(_T(""))
{

}

CPMSetting::~CPMSetting()
{
    m_SetupDataMap.RemoveAll();
}

bool CPMSetting::SaveSetting()
{
    // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
    CStdioFile setupFile;
    if (setupFile.Open(m_szSetupFileName, CFile::modeWrite | CFile::typeText))
    {
        CString szLine;
        CString szKey;
        CString szValue;

        for (POSITION pos = m_SetupDataMap.GetStartPosition(); pos != NULL; )
        {
            m_SetupDataMap.GetNextAssoc(pos, szKey, szValue);

            szLine.Format("%s = %s\n", szKey, szValue);
            setupFile.WriteString(szLine);
        }

        setupFile.Close();        
        return true;
    }

    return false;
}

bool CPMSetting::LoadSetting(LPCTSTR szSetupFileName)
{
    m_SetupDataMap.RemoveAll();
    m_szSetupFileName.SetString(szSetupFileName);

    CStdioFile setupFile;
    if (setupFile.Open(m_szSetupFileName, 
        CFile::modeCreate | CFile::modeNoTruncate | CFile::modeRead | CFile::shareDenyNone | CFile::typeText))
    {
        CString szLine;
        CString szKey;
        CString szValue;

        LPCTSTR szSeps = _T("=\t\r\n");

        while(setupFile.ReadString(szLine))
        {
            // 세팅을 한줄한줄 읽어서 넣는다.
            int nTokenPos = 0;

            if (0 != szLine.Compare(_T("")))
            {
                szKey = szLine.Tokenize(szSeps, nTokenPos);

                if (0 < nTokenPos)
                {
                    szValue = szLine.Tokenize(szSeps, nTokenPos);

                    if (0 != szKey.Compare(_T("")) && 0 != szValue.Compare(_T("")))
                    {
                        szKey.Trim();
                        szValue.Trim();

                        szKey.MakeUpper();
                        m_SetupDataMap.SetAt(szKey, szValue);
                    }
                }
            }
        }

        setupFile.Close();
        return true;
    }
    
    return false;
}

bool CPMSetting::GetSettingData(LPCTSTR szKey, CString& szValue)
{
    CString szKeyString(szKey);
    szKeyString.MakeUpper();

    return (TRUE == m_SetupDataMap.Lookup(szKeyString, szValue)) ? true : false;
}

void CPMSetting::SetSettingData(LPCTSTR szKey, LPCTSTR szValue)
{
    CString szKeyString(szKey);
    szKeyString.MakeUpper();

    m_SetupDataMap.SetAt(szKeyString, szValue);
}

CPMSetting& CPMDefaultSetting::GetInstance()
{
    static CPMSetting pmSetting;
    return pmSetting;
}

LPCTSTR CPMDefaultSetting::GetDefaultSettingName()
{
    return _T("PatchMaker.cfg");
}