#!/usr/bin/env python
"""
Footprint PCB layouting program
Copyright (C) 2012 Danny Milosavljevic
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/>.
"""

from ConfigParser import ConfigParser, NoSectionError, DuplicateSectionError
import os
from xdg import BaseDirectory

ME = "Footprint"

class ConfigParser2(ConfigParser):
	def optionxform(self, optionstr): 
		return(optionstr)

class Config(object):
	def __init__(self):
		self.__parser = ConfigParser2()
		d = BaseDirectory.save_config_path(ME)
		self.__filename = os.path.join(d, "settings")
		try:
			self.__parser.add_section("main")
		except DuplicateSectionError:
			pass
		self.__parser.set("main", "fileChooserFolder", "")
		print(self.__parser.items("main"))
		if os.path.exists(self.__filename):
			self.__parser.read(self.__filename)
		else:
			for name in reversed([x for x in BaseDirectory.load_config_paths(ME, "settings")]):
				try:
					f = open(name, "r")
					self.__parser.readfp(f, name)
					f.close()
				except IOError as e:
					print >>sys.stderr, e
				except OSError as e:
					print >>sys.stderr, e
		try:
			for name, value in self.__parser.items("main"):
				setattr(self, name, value or None)
		except NoSectionError:
			pass
	def __save(self):
		for name in dir(self):
			if not name.startswith("_") and name != "load" and name != "save":
				value = getattr(self, name)
				self.__parser.set("main", name, value)
		tempFilename = "%s.new" % (self.__filename, )
		with open(tempFilename, "w") as f:
			self.__parser.write(f)
		os.rename(tempFilename, self.__filename)
	def __setattr__(self, name, value):
		# FIXME original
		object.__setattr__(self, name, value)
		if not name.startswith("_"):
			self.__save()

config = Config()
if __name__ == "__main__":
	config.fileChooserFolder
	pass
