import string, regex
from wxPython.wx import *
import UserDict
from prefs import *
snarfdir = '.'

DefaultOpt = ' _values_'
Comments = ' _comments_'

class RcFile(UserDict.UserDict):

    _section = regex.compile('^\[\(.+\)\]')
    #_section = re.compile('^[(.+)]')
    _option = regex.compile('^\([^ \t]+\)[ \t]*=[ \t]*\(.*\)$')
    #_option = re.compile('^([^ \t]+)[ \t]*=[ \t]*(.*)$')
    def __init__(self, fn):
        self.filename = fn
        self.data = {}
        try:
            f = open(fn)
            lines = filter(None, f.readlines())
            f.close()
        except:
            lines = []
        self.data['RC'] = {}
        opt = None
        for line in lines:
            line = string.rstrip(line)
            if line == '':
                opt = None
                continue
            #m = self._section.match(line)
            #print m, line
            if self._section.match(line) >= 0:
            #if m != None:
                sect = self._section.group(1)
                if not self.data.has_key(sect):
                    self.data['RC'] = {}
                opt = None
                continue
            #m = self._option.match(line)
            #print m, line
            if self._option.match(line) >= 0:
            #if m != None:
                opt, val = self._option.group(1, 2)
                self.data['RC'][opt] = val
                continue
            if opt and line[0] == '\t':
                self.data['RC'][opt] = '%s %s' \
                    % (self.data['RC'][opt], string.lstrip(line))
                continue
            if not self.data['RC'].has_key(DefaultOpt):
                self.data['RC'][DefaultOpt] = []
            self.data['RC'][DefaultOpt].append(line)
            opt = None
        if not self.data['RC']:
            del self.data['RC']

    def write(self):

        """ Write the data back to the file """
        f = open(self.filename, "w")
        sections = self.data.keys()
        sections.sort()
        for section in sections:
            if section is not 'RC':
                f.write('\n[%s]\n' % section)
            data = self.data[section]
            names = data.keys()
            names.sort()
            for name in names:
                value = data[name]
                if name in (Comments, DefaultOpt):
                    #f.write('%s\n' % string.join(value, '\n'))
                    pass
                else:
                    f.write('%s = %s\n' % (name, value))
        f.close()


class optionSnarfFrame(wxFrame):
    def __init__(self, parent, id, title):

        """ TODO:
            * Add htl?

            * Use wxSizer instead of absolute coordinates.

        """

        wxFrame.__init__(self,parent, -1, title,wxDefaultPosition, wxSize(450,360))
        panel = wxPanel(self, -1,style=wxTAB_TRAVERSAL)
        buttonok = wxButton(panel, 1002, "Ok")
        buttonok.SetPosition(wxPoint(105, 270))

        button = wxButton(panel, 1003, "Cancel")
        button.SetPosition(wxPoint(255, 270))

        EVT_BUTTON(self, 1002, self.OnOK)
        EVT_BUTTON(self, 1003, self.OnCloseMe)
        EVT_CLOSE(self, self.OnCloseWindow)

        row = 20
        col = 170
        width = 270

        wxStaticText(panel, -1, "Freenet Directory", wxPoint(15, row), wxSize(145, 20))
        self.freenetdir = wxTextCtrl(panel, wxNewId(), "", wxPoint(col, row), wxSize(width, 20))

        wxStaticText(panel, -1, "Java location", wxPoint(15, row + 30), wxSize(145, 20))
        self.java = wxTextCtrl(panel, wxNewId(), "", wxPoint(col, row + 30), wxSize(width, 20))

        wxStaticText(panel, -1, "Freenet insert program", wxPoint(15, row + 60), wxSize(145, 20))
        self.finsert = wxTextCtrl(panel, wxNewId(), "", wxPoint(col, row + 60), wxSize(width, 20))

        wxStaticText(panel, -1, "Helper Application", wxPoint(15, row + 90), wxSize(145, 20))
        self.helper = wxTextCtrl(panel, wxNewId(), "", wxPoint(col, row + 90), wxSize(width, 20))

        wxStaticText(panel, -1, "Debug 1=yes 0=no", wxPoint(15, row + 120), wxSize(145, 20))
        self.debug = wxTextCtrl(panel, wxNewId(), "", wxPoint(col, row + 120), wxSize(width, 20))

        wxStaticText(panel, -1, "Check Fmail Interval", wxPoint(15, row + 150), wxSize(145, 20))
        self.fmailInterval = wxTextCtrl(panel, wxNewId(), "", wxPoint(col, row + 150), wxSize(width, 20))

        wxStaticText(panel, -1, "(You will need to re-start Snarfzilla for changes to take effect!)", wxPoint(15, row + 210), wxSize(430, 20))

        i = RcFile("%s/prefs.py" % snarfdir)
        freenetdir = string.replace(i.data['RC']['freenetdir'], "'", "",)
        finsert = string.replace(i.data['RC']['finsert'], "'", "",)
        java = string.replace(i.data['RC']['java'], "'", "",)
        helper = string.replace(i.data['RC']['helper'], "'", "",)
        debug = string.replace(i.data['RC']['debug'], "'", "",)
        fmailInterval = string.replace(i.data['RC']['fmailInterval'], "'", "",)
        self.freenetdir.SetValue(freenetdir)
        self.finsert.SetValue(finsert)
        self.java.SetValue(java)
        self.helper.SetValue(helper)
        self.debug.SetValue(debug)
        self.fmailInterval.SetValue(fmailInterval)

    def OnOK(self, event):
        i = RcFile("%s/prefs.py" % snarfdir)
        i.data['RC']['freenetdir'] = ("'%s'" % self.freenetdir.GetValue())
        i.data['RC']['finsert']= ("'%s'" % self.finsert.GetValue())
        i.data['RC']['java'] = ("'%s'" % self.java.GetValue())
        i.data['RC']['helper'] = ("'%s'" % self.helper.GetValue())
        i.data['RC']['debug'] = ("'%s'" % self.debug.GetValue())
        i.data['RC']['fmailInterval'] = ("'%s'" % self.fmailInterval.GetValue())
        i.write()
        self.Close(true)

    def OnCloseMe(self, event):
        self.Close(true)

    def OnCloseWindow(self, event):
        self.Destroy()
