# -*- coding: utf-8 mode: python -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

__all__ = ('config',)

from os import path
from types import StringTypes

import config as app_config
BASE_CONFIG = getattr(app_config, 'BASE_CONFIG', {})
PROD_CONFIG = getattr(app_config, 'PROD_CONFIG', {})
PROFILE = getattr(app_config, 'PROFILE', None)
PROFILES = getattr(app_config, 'PROFILES', dict(prod=PROD_CONFIG))

_error = object()
class Config(object):
    # Par défaut, ne pas lancer d'exception mais retourner None pour une clé
    # inexistante. Cependant dans ce cas il n'est plus possible d'utiliser
    # correctement la fonction getattr(). L'alternative est d'utiliser la
    # méthode get() de cette classe.
    _raise_on_error = False
    def set_raise_on_error(self, raise_on_error=True):
        self._raise_on_error = raise_on_error

    def set_appname(self, appname):
        BASE_CONFIG['appname'] = appname
    def set_basedir(self, basedir):
        BASE_CONFIG['basedir'] = basedir
    def set_profile(self, profile):
        if profile is not None and profile not in PROFILES:
            raise ValueError("%s: invalid profile" % profile)
        global PROFILE
        PROFILE = BASE_CONFIG['profile'] = profile

    def __getattr__(self, name):
        if PROFILE is not None:
            config = PROFILES[PROFILE]
            if name in config: return config[name]
        if name in BASE_CONFIG: return BASE_CONFIG[name]
        if self._raise_on_error: raise AttributeError(name)
        else: return None

    def __getitem__(self, key, default=_error):
        if PROFILE is not None:
            config = PROFILES[PROFILE]
            if key in config: return config[key]
        if key in BASE_CONFIG: return BASE_CONFIG[key]
        if default is _error and self._raise_on_error: raise KeyError(key)
        else: return default
    get = __getitem__
    def __contains__(self, key):
        if PROFILE is not None:
            config = PROFILES[PROFILE]
            if key in config: return True
        return key in BASE_CONFIG
    has_key = __contains__

config = Config()
