import rox
from rox import g, choices
import gobject
from rox.options import OptionGroup, Option
import string, os, sys, signal

done_writing = True
timeout = 750
rootwin = g.gdk.get_default_root_window()

def update_options():
	global done_writing
	if done_writing:
		done_writing = False
		gobject.timeout_add(timeout,write_options)

def write_options():
	global done_writing
	rox.app_options.save()
	orobopid=long(rootwin.property_get("_NET_WM_PID")[2][0])
	os.kill(orobopid,signal.SIGHUP)
	done_writing = True
	return False

def convert_fontname(s):
	xftname = ''
	family = ''
	s=s.replace(',',' ')
	styles = ['bold','light','medium','italic']
	for x in s.lower().split():
		for y in styles:
			if x==y: xftname += ':'+x; break
		else:
			if x.isdigit():	xftname += ':size='+x
			else: family += x+' '
	xftname = family.strip()+xftname			
	return xftname

def convert_back_fontname(s):
	fields = s.split(':')
	font = fields[0]
	size = '10'
	if len(fields)>1:
		font += ','
		for x in fields[1:]:
			if x.split('=')[0] == 'size':
				size = x.split('=')[1]
			else:
				font += ' '+x
	font = string.capwords(font)
	return font+' '+size

def parse_rc(path):
	list = {}
	f = file(path,'r')
	for l in f.readlines():
		l = l.strip()
		if not l or l[0]=='#': continue
		(key, value) = l.split('=',1)
		key=key.strip()
		value=value.strip()
		if key == 'font':
			value=convert_back_fontname(value)
		if key and value: list[key]=value
	f.close()
	return list

class OptionGroupRC(OptionGroup):
	def __init__(self, program, leaf):
		self.program = program
		self.leaf = leaf
		self.pending = {}	# Loaded, but not registered
		self.options = {}	# Name -> Option
		self.callbacks = []
		self.too_late_for_registrations = 0
		
		path = choices.load(program, leaf)
		if not path:
			return

		try:
			self.pending = parse_rc(path)
		except:
			rox.report_exception()

	def save(self):
		"""Save all option values. Usually called by OptionsBox()."""
		assert self.too_late_for_registrations

		path = choices.save(self.program, self.leaf)
		if not path:
			return	# Saving is disabled

		txt = ''
		for option in self:
			if option.value.strip():
				if option.name == 'font':
					value = convert_fontname(option.value)
				else:
					if option.int_value >= 0 and option.value.find('.'):
						value = str(int(option.int_value))
					else:
						value = option.value
				txt += option.name + '=' + value + '\n'
				
		stream = open(path, 'w')
		stream.write(txt)
		stream.close()

defaults = parse_rc(rox.app_dir + '/defaults')

def Opt(name):
	return Option(name,defaults[name])
