"""
Imports all required blueprints and initalises the app.
Runs in debug mode if ran directly.
"""

import logging
import atexit

import dotenv
import flask

import db

from blueprints.projects import projectsBP
from blueprints.booper import booperBP
from blueprints.static import staticBP

logging.basicConfig(level=logging.DEBUG)

dotenv.load_dotenv()

app = flask.Flask(__name__)
db.init()
app.register_blueprint(projectsBP)
app.register_blueprint(booperBP)
app.register_blueprint(staticBP)

def onClose():
    """
    Safely close all blueprints and then the database.
    """

    for bp in app.blueprints.values():
        # If there is an onClose function to call
        if callable(getattr(bp, "onClose", None)):
            bp.onClose()

    db.GLOBAL.close()

atexit.register(onClose)

if __name__ == '__main__':
    print('Running in debug mode')
    app.run(debug=True)
