import re
{{ vars.config.module|generate_import(alias='config') }}
{{ vars.ext|imports }}

class {{ vars.ext|class_header }}:

    def __init__(self, app=None):
        {% if vars.ext.base_classes %}
        super().__init__(app=None)
        {% endif %}
        if app:
            self.init_app(app)

    def init_app(self, app):
        """Flask application initialization."""
        {% if vars.ext.base_classes %}
        super().init_app(app=app)
        {% endif %}
        self.init_config(app)
        if not self.is_inherited():
            self.register_flask_extension(app)

    def register_flask_extension(self, app):
        {% if vars.ext.base_classes %}
        super().register_extension()
        {% endif %}
        app.extensions["{{ vars.ext.alias }}"] = self

    def init_config(self, app):
        """Initialize configuration."""
        for identifier in dir(config):
            if re.match('^[A-Z_0-9]*$', identifier) and not identifier.startswith('_'):
                if isinstance(app.config.get(identifier), list):
                    app.config[identifier] += getattr(config, identifier)
                elif isinstance(app.config.get(identifier), dict):
                    for k, v in getattr(config, identifier).items():
                        if k not in app.config[identifier]:
                            app.config[identifier][k] = v
                else:
                    app.config.setdefault(identifier, getattr(config, identifier))


    def is_inherited(self):
        from importlib_metadata import entry_points

        ext_class = type(self)
        for ep in entry_points(group='invenio_base.apps'):
            loaded = ep.load()
            if loaded is not ext_class and issubclass(ext_class, loaded):
                return True
        for ep in entry_points(group='invenio_base.api_apps'):
            loaded = ep.load()
            if loaded is not ext_class and issubclass(ext_class, loaded):
                return True
        return False

{{ vars.ext|extra_code }}
