#include "CSettings.h"

/*
	Constructor - Deconstructor
*/
CSettings::CSettings()
: mIsOpened(false)
{
}

CSettings::CSettings(const CString& pStr, const CString& pSeparator)
: mIsOpened(false)
{
	this->SetSeparator(pSeparator);
	this->loadFile(pStr);
}

/*
	File-Loading Functions
*/
bool CSettings::loadFile(const CString& pStr)
{
	// definitions
	CString fileData;

	// Clear Keys
	mKeyList.clear();

	// Load File
	if (!fileData.load(pStr))
	{
		mIsOpened = false;
		return false;
	}

	// Parse Data
	fileData.removeAllI("\r");
	strList = fileData.tokenize("\n");
	for (unsigned int i = 0; i < strList.size(); i++)
	{
		// Skip Comments
		if (strList[i][0] == '#' || strList[i].find(mStrSep) == -1)
			continue;

		// Tokenize Line && Trim && Lowercase Key Name
		std::vector<CString> line = strList[i].tokenize(mStrSep);
		line[0].toLowerI();
		if (line.size() == 1) continue;

		// Fix problem involving settings with an = in the value.
		if (line.size() > 2)
		{
			for (unsigned int j = 2; j < line.size(); ++j)
				line[1] << "=" << line[j];
		}

		// Trim
		for (unsigned int j = 0; j < line.size(); j++)
			line[j].trimI();

		// Create Key
		CString keyName = line[0].toLower();

		StringMap::iterator key = GetKey(keyName);
		if (key == mKeyList.end())
			mKeyList[keyName] = line[1];
		else
			key->second << "," << line[1];
	}

	mIsOpened = true;
	return true;
}

/*
	Get Settings
*/
bool CSettings::getBool(const CString& pKeyName, bool pDefault)
{
	StringMap::iterator key = GetKey(pKeyName);
	return (key == mKeyList.end() ? pDefault : (key->second == "true" || key->second == "1"));
}

float CSettings::getFloat(const CString& pKeyName, float pDefault)
{
	StringMap::iterator key = GetKey(pKeyName);
	return (key == mKeyList.end() ? pDefault : (float)strtofloat(key->second));
}

int CSettings::getInt(const CString& pKeyName, int pDefault)
{
	StringMap::iterator key = GetKey(pKeyName);
	return (key == mKeyList.end() ? pDefault : strtoint(key->second));
}

const CString& CSettings::getStr(const CString& pKeyName, const CString& pDefault)
{
	StringMap::iterator key = GetKey(pKeyName);
	return (key == mKeyList.end() ? pDefault : key->second);
}
