"""
    jesse.common.config
    ~~~~~~~~~~~~~~~~~~~~~~~

    读取配置文件，载入自定义字典

    :copyright: (c) 2016 by ruth.ren Team.
"""

import configparser
import os

from common.constants import CONFIG_PATH


class Config:

    def __init__(self, filename='jesse', cfg=None):

        config = configparser.ConfigParser()

        if cfg:
            config.read(cfg)
        else:
            config.read(os.path.join(CONFIG_PATH, '%s.conf' % filename))

        for section in config.sections():
            setattr(self, section, Dictionary())
            for name, raw_value in config.items(section):
                try:
                    # 避免 '0' 和 '1' 解析为boolean类型
                    if config.get(section, name) in ["0", "1"]:
                        raise ValueError

                    value = config.getboolean(section, name)
                except ValueError:
                    try:
                        value = config.getint(section, name)
                    except ValueError:
                        value = config.get(section, name)
                setattr(getattr(self, section), name, value)


class Dictionary(dict):
    """Jesse 自定义字典类型."""

    def __getattr__(self, key):
        return self.get(key, None)

    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__
