#!/bin/python
import mimetypes

from flask import Flask, request, session
from flask import url_for
from flask_admin import helpers as admin_helpers
from flask_babelex import Babel
from flask_security import Security, SQLAlchemyUserDatastore
from flask_uploads import patch_request_class

from PDMI.blueprints.admin import admin
from PDMI.blueprints.api import api, api_0_0_1
from PDMI.blueprints.front import front
from PDMI.blueprints.documentation import documentation
from PDMI.blueprints.external import external
from PDMI.models import db, Users, Roles
from PDMI.views import main_bp

# Config mimetype
mimetypes.add_type('text/css', '.css')
mimetypes.add_type('text/javascript', '.js')

server = Flask(__name__)

# Load config
server.config.from_object('PDMI.config')

# Create database
db.init_app(server)
with server.app_context():
    db.create_all(app=server)

# Setup Flask-security
user_datastore = SQLAlchemyUserDatastore(db, Users, Roles)
security = Security(server, user_datastore)

patch_request_class(server, 16 * 1024 * 1024)

# Setup babel
babel = Babel(server)


@babel.localeselector
def get_locale():
    if request.args.get('lang'):
        session['lang'] = request.args.get('lang')
    return session.get('lang', 'fr')


@security.context_processor
def security_context_processor():
    return dict(
        admin_base_template=admin.base_template,
        admin_view=admin.index_view,
        h=admin_helpers,
        get_url=url_for
    )


@server.context_processor
def utility_functions():
    def print_in_console(message):
        print(str(message))

    return dict(mdebug=print_in_console)


# Register admin
admin.init_app(server)

# Register api
api.init_app(server)
api_0_0_1.init_app(server)

server.register_blueprint(front)
server.register_blueprint(documentation)
server.register_blueprint(external)

# Register main blueprint
server.register_blueprint(main_bp)

if __name__ == '__main__':
    server.run()
