#!/usr/bin/env python
"Config-file reader/writer test project."

#	ConfEdit, reads, edits and writes config-files.
#	Copyright (C) 2008  Joakim Soderlund
#
#	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/>.

import os
import re

from UserDict import UserDict

__author__	= "Joakim Soderlund"
__version__	= "0.7"
__copyright__	= "Copyright (C) 2008  Joakim Soderlund"
__license__	= "GPLv3"

class ConfHandle(UserDict):
	"""Handles some config files (key=value\\n)."""
	def __init__(self, cfglocation=os.path.join(os.path.expanduser("~"), ".warzone2100-2.1", "config")):
		self.CFGLocation = cfglocation
		self.data = self.read()

	def read(self):
		"""Returns dictionary of the config file."""
		try:
			cfgfile = open(self.CFGLocation)
			cfglines = cfgfile.readlines()
			cfgfile.close()
			ConfVarList = []
			ConfVarDict = {}
			for a in cfglines:
				if re.search("\n$", a):
					a = a[:-1]
				if a:
					ConfVarList.append(a.split("="))
			for k, v in ConfVarList:
				ConfVarDict[k] = v
			return ConfVarDict

		except IOError:
			print "ERROR: The file %(cfglocation)s does not exist." % locals()
			exit()

	def reload(self):
		"""Reloads the config file."""
		self.data = {}
		self.data = self.read()

	def __str__(self):
		"""Returns config as a string"""
		CFGString = ''
		for a in [k for k in self.data]:
			CFGString += "%s=%s\n" % (a, self.data[a])
		return CFGString

	def write(self):
		"""Writes config file."""
		cfgfile = open(self.CFGLocation, "w")
		ConfString = str(self)
		cfgfile.write(ConfString)
		cfgfile.close()

if __name__ == "__main__":
	print __doc__


