#!/usr/bin/env python

import os
import sys

try:
	import pygtk
	pygtk.require("2.0") #wir wollen gtkv2 nutzen
	#print "pygtk importiert"
except:
	print "couldn't import 'pygtk'! Try 'apt-get install python-gtk2'."
	sys.exit(1)

try:
	import gtk
	import gtk.glade
	#print "gtk.glade importiert"
except:
	print "Mit GTKv2 kannst du den Schlafenden wecken!"
	sys.exit(1)


try:
	import configobj	## needed for reading and writing of the config file
except:
	print "couldn't import 'configobj'! Try 'apt-get install python-configobj'."
	sys.exit(1)
	
############################ CONFIG FILE ##########################

class SettingsClass(configobj.ConfigObj):
	""" a class for handling the config file(s) using configobj"""

	CONF_LOCATIONS = [
		"./in-gen.conf",
		"~/.in-gen.conf",
	]

	def __init__(self, config_file=None):
		config_file = self.__getConfigFileName(config_file)
		self.prefs = self.__getPreferences(config_file)
		#TODO: a proper ConfigObj instance knows these variables, read them automatically!


	def __getitem__(self, key):
		"""redirect all requests to the 'prefs' attribute"""
		return self.prefs[key]

	def __getPreferences(self, config_file):
		"""read the config file and return a configobj object."""
		try:
			prefs = configobj.ConfigObj(config_file)
			if prefs:
				pass
			else: 
				raise "failed to load the config file: %s" % config_file
		except IOError:
			raise "unable to open the config file: %s" % config_file
		return prefs


	def __getConfigFileName(self, config_file):
		# search for the configuration file
		import types
		if config_file is None:
			# no config file was specified - we will look for it in the ususal locations
			conf_file_list = [os.path.expanduser(f)
				for f in self.CONF_LOCATIONS
				if os.path.exists(os.path.expanduser(f))]
			if not conf_file_list:
				# no possible config file found in the usual locations
				raise "could not find a config file"
			config_file = conf_file_list[0]
		else:
			# a config file was specified (e.g. via command line)
			if type(config_file) != types.StringType:
				raise "invalid config file specified: %s" % config_file
			if not os.path.exists(config_file):
				raise "could not find the specified configuration file (%s)" % config_file
		return config_file
	
	def safe(self):
		"""safe the current values of the config to file"""
		return self.prefs.write()
	
	def createsection(self,newsection):
		"""adds a new empty section to config object"""
		self.prefs[newsection] = {}

################################# GUI ######################

class gtkgui:
	def __init__(self,gtkext):
		# gtk is given, it has to be known in the whole class
		self.gtk = gtkext
		# define which gladefile to use for frontend
		gladefile = "in-gen-glade/in-gen-glade.glade"
		self.gui = gtk.glade.XML(gladefile)
		# set button handlers
		actions = { "on_OkButton_clicked": self.clicked_ok,
			"on_mainwindow_destroy": self.exit,
			"on_SectionComboBox_changed": self.combobox_changed
				}
		# connect the actions to the events
		self.gui.signal_autoconnect (actions)
		#load config
		self.config = SettingsClass()
		#display all number systems for selection
		self.display_number_systems()
		#default section
		self.section = ""
		#display an unused invoice number
		#self.display_new_number()
	
	############################3
	def display_number_systems(self):
		"""get all available number systems from configfile, display in combobox."""
		#get all sections
		itemlist = self.config.prefs.items()
		#remove Main section (not a number system)
		if itemlist[0][0] == "Main":
			itemlist = itemlist[1:]
		#filter section names
		sections = []
		for item in itemlist:
			sections.append(item[0])
		#now fill widget data
		self.cbox = self.gui.get_widget("SectionComboBox")
		self.cbox.remove_text(0)
		for section in sections:
			self.cbox.append_text(section)
		
	
	def display_new_number(self):
		#get relevant variables
		prefix 	= self.config[self.section]["prefix"]
		lastnumber = self.config[self.section]["lastnumber"]
		suffix 	= self.config[self.section]["suffix"]
		newnumber = create_number(prefix, lastnumber, suffix)
		
		#display new number in GUI
		self.outputfield = self.gui.get_widget("NumberDisplay")
		self.outputfield.set_markup('<span size="xx-large">'+newnumber+'</span>')

		
	#### implementation of actions

	def clicked_ok(self, widget):
		"""save last generated number in config file"""
		#update "lastnumber" entry in config
		self.config[self.section]["lastnumber"] = int(self.config[self.section]["lastnumber"]) + 1
		#write config to filesystem
		self.config.safe()
		#notify user	
		number = self.config[self.section]["prefix"] + str(self.config[self.section]["lastnumber"]) + self.config[self.section]["suffix"]
		self.outputfield = self.gui.get_widget("StatusBar")
		self.outputfield.push(0,"Saved %s as last number." % number)
		#display new number in GUI
		self.outputfield = self.gui.get_widget("NumberDisplay")
		self.outputfield.set_markup("")
		#security measure to prevent a user from accidently creating a number
		self.section=""

	def combobox_changed(self,widget):
		"""display new number if the user has selected a section"""
		self.set_section(widget)
		self.display_new_number()
		
	def set_section(self, widget):
		"""sets current section according to selection in combobox"""
		model = widget.get_model()
		section = model[widget.get_active()][0]
		self.section =  section
		
	def exit(self, widget):
		gtk.main_quit()


		
		
############################# INVOICE NUMBER HANDLING ###################		

def create_number(prefix, lastnumber, suffix):
	"""gets prefix string, last used number and suffix string.
	returns new invoice number."""
	return str(prefix) + str(int(lastnumber)+1) + str(suffix)
	

############################ MAIN #################################




app = gtkgui(gtk)
gtk.main()