
#include <iostream>
#include <sstream>
#include "Config.h"
#include "exceptions.h"

using namespace std;

namespace fft
{
	
	Config::Config(const String& fileNam)
		: fileName(fileNam)
	{

		ifstream fs(fileName.c_str());
		if (!fs.good())
			throw FileNotFoundException(fileName.c_str());
		while(!fs.eof())
		{
			char buf[256];
			fs.getline(buf, 256);
			string line(buf);
				
	
			if (line[0] == '#' || line == "")
				continue;
				
			// strip comments at the end of line
			int idx = line.find('#', 0);
			if (idx >= 0)
			{
				line = line.substr(0, idx);
			}
			
			idx = line.find('=', 0);
				
			string name = line.substr(0,idx);
			string value = line.substr(idx+1);
			name = trim(name);
			value = trim(value);
			//cout << name << "=" << value << endl;
			data.insert(pair<string,Item>(name, Item(name, value)));
		}
			
		fs.close();
	}
	
	const Config::Item& Config::operator[](string name) const
	{
		map<string, Item>::const_iterator it = data.find(name);
		if (it == data.end())
			throw BaseException("Key \"%s\" not found in config file %s", name.c_str(), fileName.c_str());
		return (*it).second;
	}
	
	bool Config::hasKey(string name) const
	{
		return data.find(name) != data.end();
	}
	
	string Config::trim(string str)
	{
		string ret = str;
		unsigned idx = 0;
		
		// find first not-space character in string
		for (; (ret[idx] == ' ' || ret[idx] == '\t') && idx < ret.length(); idx++);
		// remove spaces before not-space first
		if (idx > 0)
			ret = ret.substr(idx);
		
		// find last not-psace character in string
		for(idx = ret.length() - 1; (ret[idx] == ' ' || ret[idx] == '\t') && idx >= 0; idx--);
		// remove spaces after last not-space chracter
		if (idx < ret.length() - 1)
			ret = ret.substr(0, idx + 1);
			
		return ret;
	}
	
	
	
}

