# Copyright (c) 2000-2001 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# 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.

"""config"""

__revision__ = "$Id: config.py,v 1.21 2001/12/07 16:01:33 syt Exp $"

import os,os.path

_CONFIG = {}
_home_set_manually = 0
_share_set_manually = 0

import sys

if sys.platform == 'win32':
    default_home_dir_name = 'narval_data'
    default_config_name = os.path.join(os.environ['windir'],
                                       'narval.conf')
    from narval import __version__
    def get_registry_info():
        d = {}
        key_name = "Software\\Logilab\\Narval\\%s\\config"%__version__
        try:
            import _winreg
            key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                  key_name)
            for i in range(_winreg.QueryInfoKey(key)[1]):
                (name,value,_)=_winreg.EnumValue(key,i)
                d[name.lower()] = value.encode('mbcs')
            key.Close()
        except:
            print 'problem accessing registry HKLM\\%s'%key_name
        try:
            key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                  key_name)
            for i in range(_winreg.QueryInfoKey(key)[1]):
                (name,value,_)=_winreg.EnumValue(key,i)
                d[name.lower()] = value.encode('mbcs')
            key.Close()
        except:
            pass
        if not d.has_key('home'):
            key_name = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"
            try:
                key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                      key_name)
                for i in range(_winreg.QueryInfoKey(key)[1]):
                    (name,value,_)=_winreg.EnumValue(key,i)
                    if name == 'AppData':
                        d['home'] = os.path.join(value.encode('mbcs'),
                                                 default_home_dir_name)  
                        break
            except:
                print 'problem accessing registry HKCU\\%s to get NARVAL_HOME. Using defaults.'%key_name
        return d
            
        
    
    def load_config(path=None) :
        CONFIG = get_registry_info()
        if not CONFIG :
            try:
                exec( open(path or default_config_name).read() )
            except IOError :
                print 'No config file %s found, using defaults...' % path
        _CONFIG.update(CONFIG)

        
else:
    default_home_dir_name = '.narval'
    default_config_name = '/etc/narval.conf'
    def load_config(path=None) :
        path = path or default_config_name
        try:
            CONFIG = {}
            exec( open(path).read() )
            _CONFIG.update(CONFIG)
        except IOError :
            print 'No config file %s found, using defaults...' % path
    
def get_home() :
    if _home_set_manually :
        return _CONFIG.get('home',None)
    else:
        return os.environ.get('NARVAL_HOME',None) or \
               _CONFIG.get('home',None) or \
               os.path.normpath(os.path.join(os.environ.get('HOME','/'),
                                             default_home_dir_name))

def set_home(path) :
    global _home_set_manually
    if path != _CONFIG.get('home',None):
        _home_set_manually = 1
    _CONFIG['home'] = path
    try:
        os.listdir(path)
        for directory in ['data', 'dtd', 'extensions', 'graphics',
                          'modules', 'recipes', 'transforms']:
            os.listdir(os.path.join(_CONFIG['home'],directory))
    except:
        return 0
    return 1

def create_home_subdirs():
    try:
        os.listdir(get_home())
    except:
        os.mkdir(get_home())
        
    for directory in ['data', 'dtd', 'extensions', 'graphics',
                      'modules', 'recipes', 'transforms']:
        try:
            os.listdir(os.path.join(get_home(),directory))
        except:
            os.mkdir(os.path.join(get_home(),directory))
    for req_config_file in ['dtd/CATALOG', 'dtd/Narval.dtd', 'data/horn_preferences.xml']:
        from os.path import join, normpath, isfile
        f_path = normpath(join(get_home(),req_config_file))
        if not os.path.isfile(f_path):
            from shutil import copy
            copy(normpath(join(get_share(), req_config_file)), f_path)
    #  update catalog
    from bibal import update_catalog
    update_catalog()

    
def get_share() :
    if _share_set_manually:
        return _CONFIG.get('share',None)
    else:
        return os.environ.get('NARVAL_SHARE',None) or \
               _CONFIG.get('share',None) or \
               '/usr/share/narval/'

def set_share(path=None) :
    global _share_set_manually
    _share_set_manually = 1
    _CONFIG['share'] = path


load_config()
    
