# -*- coding: utf-8 -*-
"""
rio.setup
~~~~~~~~~
"""

from os import environ
from flask import Flask

from .core import db
from .core import celery
from .core import redis
from .core import cache
from .core import sentry
from .core import migrate

def configure_app(app):
    """Configure Flask/Celery application.

    * Rio will find environment variable `RIO_SETTINGS` first::

        $ export RIO_SETTINGS=/path/to/settings.cfg
        $ rio worker

    * If `RIO_SETTINGS` is missing, Rio will try to load configuration
      module in `rio.settings` according to another environment
      variable `RIO_ENV`. Default load `rio.settings.dev`.

        $ export RIO_ENV=prod
        $ rio worker
    """
    app.config_from_object('rio.settings.default')

    if environ.get('RIO_SETTINGS'):
        app.config_from_envvar('RIO_SETTINGS')
        return

    config_map = {
        'dev': 'rio.settings.dev',
        'stag': 'rio.settings.stag',
        'prod': 'rio.settings.prod',
        'test': 'rio.settings.test',
    }

    rio_env = environ.get('RIO_ENV', 'dev')
    config = config_map.get(rio_env, config_map['dev'])
    app.config_from_object(config)


def register_blueprints(app):
    """Register blueprints to application.

    Currently, Rio registered:

    * /api/1
    * /dashboard
    """

    from .blueprints.event import bp as event_bp
    app.register_blueprint(event_bp, url_prefix='/event')

    from .blueprints.api_1 import bp as api_1_bp
    app.register_blueprint(api_1_bp, url_prefix='/api/1')

    from .blueprints.dashboard import bp as dashboard_bp
    app.register_blueprint(dashboard_bp, url_prefix='/dashboard')

def init_core(app):
    """Init core objects."""
    from rio import models # noqa
    db.init_app(app)
    celery.init_app(app)
    redis.init_app(app)
    cache.init_app(app)
    sentry.init_app(app)
    migrate.init_app(app, db)

def create_app():
    """Flask application factory function."""
    app = Flask(__name__)
    app.config_from_envvar = app.config.from_envvar
    app.config_from_object = app.config.from_object
    configure_app(app)
    init_core(app)
    register_blueprints(app)
    return app

@@ -78,21 +78,18 @@
 rom 
-flask
+os
  import 
 Flas
@@ -84,21 +84,20 @@
  import 
-Flask
+path
 %0A%0Afrom .
@@ -1642,16 +1642,155 @@
 oard')%0A%0A
+%0Adef get_migration_assets():%0A    %22%22%22Get absolute path of migration assets.%22%22%22%0A    return path.join(path.dirname(__file__), 'migrations')%0A%0A%0A
 def init
@@ -2015,287 +2015,40 @@
 , db
-)%0A%0Adef create_app():%0A    %22%22%22Flask application factory function.%22%22%22%0A    app = Flask(__name__)%0A    app.config_from_envvar = app.config.from_envvar%0A    app.config_from_object = app.config.from_object%0A    configure_app(app)%0A    init_core(app)%0A    register_blueprints(app)%0A    return app
+, directory=get_migration_assets())
 %0A

set migrations directory absolute.