from flask import Flask, render_template
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_pagedown import PageDown
from .models import db, User, Role
from .config import configs


def register_blueprints(app):
    from .handler import front, user, admin
    for i in [front, user, admin]:
        app.register_blueprint(i)


def register_extensions(app):
    bootstrap = Bootstrap(app)
    moment = Moment(app)
    db.init_app(app)
    migrate = Migrate(app, db)
    register_blueprints(app)
    mail = Mail(app)
    pagedown = PageDown()
    pagedown.init_app(app)
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'front.login'
    login_manager.session_protection = 'strong'

    @login_manager.user_loader
    def user_loader(id):
        return User.query.get(id)
    

def create_app(config):
    app = Flask(__name__)
    app.config.from_object(configs.get(config))
    register_blueprints(app)
    register_extensions(app)

    @app.errorhandler(404)
    def not_found(error):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def internal_server_error(error):
        return render_template('500.html'), 500

    return app
