#!/usr/bin/env python

import os

from . import env, heroku


class AppConfig(object):
    def __init__(self, app=None, *args, **kwargs):
        if app:
            self.init_app(app, *args, **kwargs)

    def init_app(self, app,
                 configfile=None, envvar=True, default_settings=True,
                 from_envvars='json', from_envvars_prefix=None):

        if from_envvars_prefix is None:
            from_envvars_prefix = app.name.upper() + '_'

        if default_settings is True:
            try:
                app.config.from_object(app.name + '.default_config')
            except ImportError:
                # ignore import errors if settings were autogenerated
                pass
        elif default_settings:
            app.config.from_object(default_settings)

        # load supplied configuration file
        if configfile:
            app.config.from_pyfile(configfile)

        # load configuration file from environment
        if envvar is True:
            envvar = app.name.upper() + '_CONFIG'

        if envvar and envvar in os.environ:
            app.config.from_envvar(envvar)

        # load environment variables
        if from_envvars:
            env.from_envvars(app.config, from_envvars_prefix,
                             as_json=('json' == from_envvars))

        # register extension
        app.extensions = getattr(app, 'extensions', {})
        app.extensions['appconfig'] = self


class HerokuConfig(AppConfig):
    def init_app(self, app, *args, **kwargs):
        super(HerokuConfig, self).init_app(app, *args, **kwargs)

        heroku.from_heroku_envvars(app.config)
