# GNU Solfege - eartraining for GNOME
# Copyright (C) 2000, 2001  Tom Cato Amundsen
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

# This module implement the parts of gnome.config that is
# needed to run Solfege.
# Yes I know this is ugly.

import string, types, re
from src import configureoutput
import os, os.path, pickle, sys

PACKAGE="solfege%s.%s" % (configureoutput.MAJOR_VERSION,
                          configureoutput.MINOR_VERSION)

if sys.platform == "win32" or os.path.isfile("debian-solfege.py.in"):
    DEFAULTS_FILENAME = "default.config"
else:
    DEFAULTS_FILENAME = os.path.join(configureoutput.sysconfdir, "solfege%s.%s"
      % (configureoutput.MAJOR_VERSION, configureoutput.MINOR_VERSION))

if sys.platform == "win32":
    USER_FILENAME = os.path.expanduser("~/solfegerc%s.%s"
        % (configureoutput.MAJOR_VERSION, configureoutput.MINOR_VERSION))
else:
    USER_FILENAME = os.path.expanduser("~/.solfegerc%s.%s"
        % (configureoutput.MAJOR_VERSION, configureoutput.MINOR_VERSION))

section_re = re.compile("\[(.*?)\]")
value_re = re.compile("(.*?)=(.*)")

def split(key):
   if "/" in key:
       return string.split(key, "/")
   else:
       return string.split(key, "\\")

def parse_file_into_dict(dict, filename):
    file = open(filename, "r")
    line = file.readline()
    section = None
    while line:
        section_m = section_re.match(line)
        value_m = value_re.match(line)
        if section_m:
            section = section_m.groups()[0]
            if not dict[PACKAGE].has_key(section):
                dict[PACKAGE][section] = {}
        elif value_m:
            assert section
            dict[PACKAGE][section][value_m.groups()[0]] = value_m.groups()[1]
        elif line == "\n":
            pass
        else:
           raise "X"
        line = file.readline()
    file.close()
    return dict


def sync():
    dump(data, USER_FILENAME)

def _maybe_create_key(key):
    global data
    app, section, k = split(key)
    if not data.has_key(app):
        data[app] = {}
    if not data[app].has_key(section):
        data[app][section] = {}

def set_int(key, val):
    global data
    assert type(val) == types.IntType
    _maybe_create_key(key)
    app, section, k = split(key)
    data[app][section][k] = str(val)

def get_int(key):
   if len(string.split(key, "=")) == 2:
      key, default = string.split(key, "=")
   else:
      default = 0
   app, section, k = split(key)
   try:
       return int(float(data[app][section][k]))
   except KeyError:
       return int(default)

def set_float(key, val):
    global data
    assert type(val) == types.FloatType
    _maybe_create_key(key)
    app, section, k = split(key)
    data[app][section][k] = str(val)

def get_float(key):
   if len(string.split(key, "=")) == 2:
      key, default = string.split(key, "=")
   else:
      default = 0
   app, section, k = split(key)
   try:
       return float(data[app][section][k])
   except KeyError:
       return float(default)

def get_string(key):
    if key[0] == "=": # = not supported yet
        return None
    if len(string.split(key, "=")) == 2:
        key, default = string.split(key, "=")
    else:
        default = ""
    app, section, k = split(key)
    try:
        return data[app][section][k]
    except KeyError:
        return default

def set_string(key, val):
    global data
    _maybe_create_key(key)
    app, section, k = split(key)
    data[app][section][k] = val

def get_vector(key):
    _maybe_create_key(key)
    app, section, k = split(key)
    try:
        return string.split(data[app][section][k])
    except KeyError:
        return []

def set_vector(key, val):
    global data
    if type(val) == types.StringType:
        val = [val]
    s = ""
    for x in val:
       s = s + x + " "
    s = string.strip(s)
    _maybe_create_key(key)
    app, section, k = split(key)
    data[app][section][k] = s

def set_bool(key, val):
    global data
    _maybe_create_key(key)
    if val:
        set_string(key, "true")
    else:
        set_string(key, "false")

def get_bool(key):
    if get_string(key) == "true":
        return 1
    else:
        return 0

def clean_file(fn):
    global data
    data = {PACKAGE:{}}
    data = parse_file_into_dict(data, DEFAULTS_FILENAME)

def clean_section(section):
    global data
    data[PACKAGE][section] = {}

def clean_key(key):
    global data
    assert prefix == None
    _maybe_create_key(key)
    app, section, k = split(key)
    data[app][section][k] = ""

def dump(dict, fn):
    f = open(fn, 'w')
    for section in dict[PACKAGE].keys():
        f.write("[%s]\n" % section)
        for name in dict[PACKAGE][section].keys():
            f.write("%s=%s\n" % (name, dict[PACKAGE][section][name]))
        f.write("\n")
    f.close()

prefix = None
data = {PACKAGE:{}}

data = parse_file_into_dict(data, DEFAULTS_FILENAME)

if not os.path.exists(os.path.expanduser("~")):
    os.makedirs(os.path.expanduser("~"))
if os.path.isfile(USER_FILENAME):
    data = parse_file_into_dict(data, USER_FILENAME)

