#===================================
#         config_store
#  Copyright 2010 - Nathan Osman
#
#   Provides a convenient way to
#   store settings pertaining to
# the preferences of the application
#
#   StackApplet is released under
#        the MIT license
#===================================

import os

CONFIG_FILE_PATH = os.path.join(os.path.expanduser("~"),".stackapplet")
CONFIG_FILE_NAME = os.path.join(CONFIG_FILE_PATH,"config")

# We need to import a JSON library
# Here we try to load two common ones

try:
    import json
except ImportError:
    import simplejson as json

class config_store:

	# Constructor
	
	def __init__(self):
		
		# We'll start with a blank slate
		
		self.data = {}
	
	# This function loads the settings from
	# our config file
	def load_settings(self):
		
		# Begin by trying to open the file
		
		try:
		
			global CONFIG_FILE_PATH, CONFIG_FILE_NAME
			
			f = open(CONFIG_FILE_NAME,'r')
			
			# The file is open... read the JSON
			# data from it
			
			self.data = json.loads(f.readline())
			
			f.close()
			
		except Exception,e:
		
			# If there is a problem (like the file
			# can't be opened) just ignore it
			
			pass
	
	def save_settings(self):
		
		# Begin by serializing the contents of our
		# data collection
		
		serialized_data = json.dumps(self.data)
		
		# Make sure that the directories that we need exist
		
		try:
			global CONFIG_FILE_PATH
			
			os.makedirs(CONFIG_FILE_PATH)
			
		except Exception,e:
		
			# If there is a problem, assume that
			# the dorectory already exists
			
			pass
		
		f = open(CONFIG_FILE_NAME,'w')
		
		f.write(json.dumps(self.data))
		
		f.close()
	
	def get_val(self,name,default_value):
		
		# Check to see if the key
		# exists in our data collection
		
		if name in self.data:
			return self.data[name]
		else:
			# We also want to store the default
			# value so that next time, we'll get
			# that instead
			
			self.data[name] = default_value
			return default_value;
	
	def set_val(self,name,value):
		
		self.data[name] = value
