# Config.py
#
# Moleskine: a source code editor for the GNOME desktop
#
# Copyright (c) 2000 - 2002   Michele Campeotto <micampe@micampe.it>
#
# 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 Library 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.

from UserDict import UserDict
import os.path
import string

import gnome.config

class Config(UserDict):
    def __init__(self, prefix):
        UserDict.__init__(self)
        if prefix[-1] != '/':
            prefix = prefix + '/'
        if prefix[0] == '/':
            prefix = prefix[1:]
        self.prefix = prefix
    
    def __setitem__(self, key, item):
        if not '/' in key:
            raise KeyError(_('Keys must be in the form "section/key"'))
        UserDict.__setitem__(self, key, item)
    
    def __getitem__(self, key):
        if not '/' in key:
            raise KeyError(_('Keys must be in the form "section/key"'))
        if not self.data.has_key(key):
            gnome.config.push_prefix(self.prefix)
            self.data[key] = gnome.config.get_string(key)
            if self.data[key] == 'None':
                self.data[key] = None
            gnome.config.pop_prefix()
            gnome.config.drop_file(self.prefix)
        return self.data[key]
    
    def has_key(self, key):
        if not '/' in key:
            raise KeyError(_('Keys must be in the form "section/key"'))
        return UserDict.has_key(self, key)
    
    def save(self):
        gnome.config.clean_file(self.prefix)
        gnome.config.push_prefix(self.prefix)
        
        for k, v in self.data.items():
            gnome.config.set_string(k, str(v))
        
        gnome.config.pop_prefix()
        gnome.config.sync()
        gnome.config.drop_file(self.prefix)
