# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.

"""Invenio environment configuration."""

from __future__ import absolute_import, print_function

import ast
import os


class InvenioConfigEnvironment(object):
    """Load configuration from environment variables.

    .. versionadded:: 1.0.0
    """

    def __init__(self, app=None, prefix='INVENIO_'):
        """Initialize extension."""
        self.prefix = prefix
        if app:
            self.init_app(app)

    def init_app(self, app):
        """Initialize Flask application."""
        prefix_len = len(self.prefix)
        for varname, value in os.environ.items():
            if not varname.startswith(self.prefix):
                continue

            # Prepare values
            varname = varname[prefix_len:]
            value = value or app.config.get(varname)

            # Evaluate value
            try:
                value = ast.literal_eval(value)
            except (SyntaxError, ValueError):
                pass

            # Set value
            app.config[varname] = value
