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 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 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 = ''
        print defaults
        #for option in self:
            #print  option

        for option in self:
            if option.value.strip():
                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])
