from flask import Blueprint

def {{ vars.app_blueprint.function|base_name }}(app):
    blueprint = Blueprint("{{ vars.app_blueprint.alias }}_app", __name__, url_prefix="{{ vars.resource_config.base_url }}")
    blueprint.record_once(init_{{ vars.app_blueprint.function|base_name }})

    #calls record_once for all other functions starting with "init_addons_"
    #https://stackoverflow.com/questions/58785162/how-can-i-call-function-with-string-value-that-equals-to-function-name
    funcs = globals()
    funcs = [v for k, v in funcs.items() if k.startswith("init_addons_{{ vars.module.suffix_snake }}") and callable(v)]
    for func in funcs:
        blueprint.record_once(func)

    return blueprint

def init_{{ vars.app_blueprint.function|base_name }}(state):
    """Init app."""
    app = state.app
    ext = app.extensions["{{ vars.ext.alias }}"]

    {%  if not vars.service_config.skip %}
    # register service
    sregistry = app.extensions["invenio-records-resources"].registry
    sregistry.register(ext.{{ ext.ext_service_name }}, service_id=ext.{{ ext.ext_service_name }}.config.service_id)
    {% endif  %}

    {%  if not vars.mapping.skip %}
    # Register indexer
    if hasattr(ext.{{ ext.ext_service_name }}, "indexer"):
        iregistry = app.extensions["invenio-indexer"].registry
        iregistry.register(ext.{{ ext.ext_service_name }}.indexer, indexer_id=ext.{{ ext.ext_service_name }}.config.service_id)
    {% endif  %}

{{ vars.app_blueprint.extra_code }}