// SettingsManager.cpp
// ```````````````````

#include "stdafx.h"
#include "SettingsManager.h"
using namespace std;


// Construction / Deconstruction (RAII)
// ====================================

SettingsManager::SettingsManager() {
	TSTRING szConfFile( _T(APPLICATION_TITLE) _T(CONF_EXTENSION) );
	data = ini_read(szConfFile);	
}

SettingsManager::~SettingsManager() {
	this->commit();
	if (inst != 0) delete inst;
}

// Singleton acquisition
// =====================

SettingsManager* SettingsManager::inst = 0;
SettingsManager* SettingsManager::getInst() {
	if (inst == 0) inst = new SettingsManager();
	return inst;
}

// Methods
// =======

string SettingsManager::get(string key, const char* default_str) {
	SettingsManager* inst = SettingsManager::getInst();

	string def(default_str);
	ini_t::const_iterator i = inst->data.find(APPLICATION_TITLE);
	if (i == inst->data.end()) {
		set(key, default_str);
		return def;
	}

	map<string,string>::const_iterator j = i->second.find(key);
	if (j == i->second.end()) {
		set(key, default_str);
		return def;
	}

	return j->second;
}

int  SettingsManager::get(string key, int default_int) {
	char default_str[64];
	sprintf_s(default_str, "%d", default_int);
	return atoi(SettingsManager::get(key, default_str).c_str());
}

void SettingsManager::set(string key, const char* val) {
	SettingsManager* inst = SettingsManager::getInst();
	inst->data[APPLICATION_TITLE][key] = val;
}

void SettingsManager::set(string key, int val) {
	char val_str[64];
	sprintf_s(val_str, "%d", val);
	SettingsManager::set(key, val_str);
}

void SettingsManager::commit() {
	SettingsManager* inst = SettingsManager::getInst();
	TSTRING szConfFile( _T(APPLICATION_TITLE) _T(CONF_EXTENSION) );
	ini_write(szConfFile, inst->data);
}