
#include "settingsmanager.h"

#include <iostream.h>

#include <qfile.h>
#include <qtextstream.h>

SettingsManager* SettingsManager::m_pInstance = 0;

SettingsManager::SettingsManager()
{
	m_Settings.setAutoDelete(true);
}


SettingsManager::~SettingsManager()
{
}


SettingsManager*
SettingsManager::instance()
{
	if(m_pInstance == 0)
		m_pInstance = new SettingsManager;

	return m_pInstance;
}


/*
  Returns true if key is found, false otherwise.  This
  is useful to set default values.
*/

bool
SettingsManager::isSet(
	const QString& key) const
{
	QString *r = m_Settings.find(key);

	if(r == 0)
		return false;
	else
		return true;
}



void
SettingsManager::setBool(
	const QString& key,
	bool value)
{
	if(value)
		set(key, "true");
	else
		set(key, "false");
}


void
SettingsManager::set(
	const QString& key,
	const QString& value)
{
	m_Settings.replace(key, new QString(value));
}


bool
SettingsManager::getBool(
	const QString& key) const
{
	QString *r = m_Settings.find(key);

	bool rc;
	
	// For simplicity, we default to false if the key was not found.
	if(r == 0)
		rc = false;
	else if(*r == "true")
		rc = true;
	else
		rc = false;

	return rc;
}


QString
SettingsManager::getString(
	const QString& key) const
{
	QString *r = m_Settings.find(key);
	QString value;

	if(r == 0)
		value = "";
	else
		value = *r;

	return value;
}


int
SettingsManager::getValue(
	const QString& key) const
{
	return getString(key).toInt();
}


void
SettingsManager::save()
{
	QFile f("settings");

	if(f.open(IO_WriteOnly | IO_Raw | IO_Truncate))
	{
		QTextStream s(&f);

		QDictIterator<QString> it(m_Settings);

		while(it.current())
		{
			s << it.currentKey().latin1() << " "
			  << *it.current() << endl;
			++it;
		}
	}
}


void
SettingsManager::load()
{
	QFile f("settings");

	if(f.open(IO_ReadOnly))
	{
		QTextStream s(&f);
		QString line, key, value;
		int space;

		while( ! s.atEnd())
		{
			line	= s.readLine();
			space	= line.find(' ');
			key		= line.left(space);
			value	= line.right(line.length() - space - 1);

			m_Settings.replace(key, new QString(value));
		}
	}
}

