//	ConfigFile.cpp - Class used to store and load application config details.
//  ----------------------------------------------------------------------------
//	This file is part of 'NiallsAVLib', base code for any kind of audiovisual
//	apps.
//	Copyright (C) 2012  Niall Moody
//	
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.
//	----------------------------------------------------------------------------

#include "AppSettings.h"
#include "ConfigFile.h"

#include <sstream>

using std::wstringstream;
using std::wstring;
using std::endl;
using std::map;

//------------------------------------------------------------------------------
ConfigFile::ConfigFile(const CmdLineParams& cmdLine):
phil(FilePath::getAppDataPath().getChild(AppSettings::applicationName).getChild(L"config.txt")),
existing(false)
{
	int i;

	//Fill out parameters.
	for(i=0;i<cmdLine.getNumRegisteredParams();++i)
	{
		parameters.insert(make_pair(cmdLine.getRegisteredParamShort(i),
									L""));
	}

	//If it exists, load the contents of parameters from the config file.
	if(phil.exists())
	{
		wstring tempstr;

		existing = true;

		while(!phil.readLine(tempstr))
		{
			wstring token;
			wstring value;

			token = tempstr.substr(0, tempstr.find_first_of(L' '));
			value = tempstr.substr(tempstr.find_first_of(L' ')+1);

			if((token.length() > 0) && (value.length() > 0))
				parameters[token] = value;
		}
	}
}

//------------------------------------------------------------------------------
ConfigFile::~ConfigFile()
{
	wstringstream tempstr;
	map<wstring, wstring>::iterator it;

	if(!phil.exists())
	{
		for(it=parameters.begin();it!=parameters.end();++it)
		{
			if(it->second != L"")
			{
				tempstr.str(L"");
				tempstr.clear();

				tempstr << it->first << L" " << it->second << endl;

				phil.writeText(tempstr.str());
			}
		}
	}
}

//------------------------------------------------------------------------------
void ConfigFile::setParameterValue(const wstring& token, const wstring& value)
{
	parameters[token] = value;
}
