# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""

from flask import Flask, url_for
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from importlib import import_module
from logging import basicConfig, DEBUG, getLogger, StreamHandler
from os import path
from babel.dates import format_date, format_datetime, format_time

db = SQLAlchemy()
login_manager = LoginManager()

def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)

def register_blueprints(app):
    # from app import base
    # app.register_blueprint(base, url_prefix="/base")
    # from app import home
    # app.register_blueprint(home, url_prefix="/home")
    for module_name in ('base', 'home'):
        module = import_module('app.{}.routes'.format(module_name))
        app.register_blueprint(module.blueprint)

def configure_database(app):

    @app.before_first_request
    def initialize_database():
        db.create_all()

    @app.teardown_request
    def shutdown_session(exception=None):
        db.session.remove()

def create_app(config):
    app = Flask(__name__, static_folder='base/static')
    app.config.from_object(config)
    register_extensions(app)
    register_blueprints(app)
    configure_database(app)

    app.jinja_env.add_extension("jinja2.ext.loopcontrols")

    @app.template_filter()
    def format_dt(value, format='medium'):
        if format == 'full':
            format="MM/dd/yyyy HH:mm"
        elif format == 'medium':
            format="MM/dd/yyyy"
        return format_datetime(value,format)
    return app
