## ------------------------------------------------------------------------
## iSiLK - A python-based graphical user interface for SiLK
## ------------------------------------------------------------------------
## Copyright (c) 2007-2008 Carnegie Mellon University. All Rights Reserved.
## ------------------------------------------------------------------------
## Authors: Andrew Kompanek (ajk@cert.org)
## ------------------------------------------------------------------------
## GNU General Public License (GPL) Rights pursuant to Version 2, June 1991
## Government Purpose License Rights (GPLR) pursuant to DFARS 252.225-7013
## ------------------------------------------------------------------------
## See the LICENSE file included in this distribution
## ------------------------------------------------------------------------

__all__ = [
    "fgloboptions",
    "filteroptions",
    "viewoptions",
    "silk",
    "dateutils",
]
import xmlutils
import wx, os, os.path, pickle
import re
import logging
import string

class ViewOptions (dict):
    def __init__(self, *args, **kargs):
        dict.__init__(self, *args, **kargs)
    def _xml_children_(self):
        return []
    def __getitem__(self, k):
        if dict.__contains__(self, k):
            return dict.__getitem__(self, k)
        else:
            return config.viewoptions[k]

class OptionsGroup (dict):
    def __init__(self, dictval):
        self._sorted_labels = []
        new_dict = {}
        labels = dictval.keys()
        labels.sort()
        for label in labels:
            val=dictval[label]
            # Strip off the number (only there so we could sort)
            r = re.compile("^\(\d+\) ")
            label = r.sub("", label, 1)
            self._sorted_labels.append(label)
            new_dict[label] = val
        dict.__init__(self, new_dict)
        
    # Convert back to a dictionary
    def todict(self):
        the_dict = {}
        for i,k in enumerate(self._sorted_labels):
            indexed_key = "(%03d) %s" % (i, k)
            if self[k] == None:
                the_dict[indexed_key] = ""
            else:
                the_dict[indexed_key] = self[k]
        return the_dict
    
    def keys(self):
        return self._sorted_labels
        
    def _xml_children_(self):
        return []
        
def _save_prefs(facility, prefs, pref_list):
    if wx.Platform == '__WXMAC__':
        prefsDir =  os.path.join(os.environ["HOME"], ".isilk")
    else:
        prefsDir = os.path.join(wx.StandardPaths.Get().GetUserConfigDir(),
            "iSiLK") 
    fname = os.path.join(prefsDir, "%s.conf" % facility)
    f = open(fname, "w")
    for p in pref_list:
        f.write("%s = %s\n" % (p, prefs[p]))
    f.close()
    
def getPreferencesDir():
    # Do the unixy thing on the Mac rather than using
    # ~/Library/Application Support/.isill
    if wx.Platform == '__WXMAC__':
        prefsDir =  os.path.join(os.environ["HOME"], ".isilk")
    else:
        prefsDir = os.path.join(wx.StandardPaths.Get().GetUserConfigDir(),
            "iSiLK")
    return prefsDir    
    
def _read_prefs(facility, prefs, pref_list):
    # Read user preferences.  These override everything else.
    prefsDir = getPreferencesDir()
    fname = os.path.join(prefsDir, "%s.conf" % facility)
    if not os.path.exists(prefsDir):
        print "Preferences directory doesn't exist.  Creating it."
        # create the directory
        os.mkdir(prefsDir)
        return False
    print "Parsing preferences file: %s" % fname
    try:
        f = open(fname)
    except:
        print "Preferences file doesn't exist."
        return False
    while True:
        l = f.readline()
        if not l: break
        #l = l.replace(" ", "")
        l = l.replace("\n","")
        if l == "" or l.find("#") != -1:
            continue
        (k,v) = l.split("=")
        k = k.replace(" ", "")
        v = string.lstrip(v, " \n\t")
        print "Read preference %s = %s" % (k,v)
        prefs[k] = v
    f.close()
    return True
    
def _read_site_config(name):
    # If present, read the fglob configuration
    filename = os.path.join(getPreferencesDir(), "site-%s.conf" % name)
    if not os.path.exists(filename):
        return
    print "Site configuration file: %s" % filename
    inf = open(filename, "r")
    options = []
    while True:
        try:
            option = pickle.load(inf)
            options.append(option)
        except EOFError:
            break
    print "options = %s" % options
    return options
    
def _xml_read_site_config(name):
    filename = os.path.join(getPreferencesDir(), "site-%s.xml" % name)
    f = open(filename, "r")
    s = f.read()
    f.close()
    options= xmlutils.xmlPickler().parseString(s)
    return options
    
def _xml_save_site_config(name, options):
    filename = os.path.join(getPreferencesDir(), "site-%s.xml" % name)
    x = xmlutils.xmlPickler().toxml(options)
    print "xml = %s" % x.toxml()
    f = open(filename, "w")
    f.write(x.toprettyxml())
    f.close()
    
def _save_site_config(name, options):
    filename = os.path.join(getPreferencesDir(), "site-%s.conf" % name)
    outf = open(filename, "w")
    for option in options:
        pickle.dump(option, outf)
    outf.close()

    