#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: Config.py 9621 2016-04-06 13:36:10Z Eric $
#
# Copyright (c) 2012 Nuwa Information Co., Ltd, All Rights Reserved.
#
# Licensed under the Proprietary License,
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at our web site.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $Author: Eric $
# $Date: 2016-04-06 21:36:10 +0800 (Wed, 06 Apr 2016) $
# $Revision: 9621 $

import os

from Iuppiter.Util import OrderedDict, SafeConfigParser

class Parser(SafeConfigParser):
    # Make it option name case-sensitive.
    def optionxform(self, optionstr):
        return optionstr

def load(f=None, engine=None, section=None):
    """
    Load configuration from environment or file.
    It will try Iuno.browser.ini or IUNO_BROWSER_CONFIG environment variable
    first, then merge with Iuno.browser.<engine>.ini and
    IUNO_BROWSER_<ENGINE>_CONFIG.

    @param f Configuration file, if it provided, this function won't load
             default configuration file.
    @param engine Browser implementation engine.
    @return Dictionary that contains 'Client' configurations.
    """
    # Load one file.
    def _load(f, engine):
        prefix = '.'.join(__name__.split('.')[:-1])
        if engine:
            prefix = '%s.%s' % (prefix, engine)

        if not f:
            key = prefix.replace('.', '_').upper()

            # Load config file from environment.
            f = os.environ.get('%s_CONFIG' % key, None)

        if not f or not os.path.exists(f):
            f = '%s.ini' % prefix

        if not os.path.exists(f):
            return {}

        parser = Parser()
        parser.read(f)

        if not section is None:
            _section = section
        else:
            _section = '%s.Client' % prefix
        if parser.has_section(_section):
            return dict(parser.items(_section))
        else:
            return {}

    if not f:
        config = _load(f, None) # Global
        if engine:
            config.update(_load(f, engine))

        return config
    else:
        return _load(f, engine)
