import os
from flask import Flask, session

from .models import db
from .views import admin, send
from .utils import get_static_hash


def create_app():
    app = Flask(__name__, static_folder='/work/static')

    environment = os.environ.get('OVERHEARD_CONFIG', 'config.Development')
    print('Using {}'.format(environment))
    app.config.from_object(environment)

    static_hash = get_static_hash()
    print('Using static version {}'.format(static_hash))

    admin.init(app)
    send.init(app)

    @app.context_processor
    def set_static_hash():
        if app.config['DEBUG']:
            static_hash = get_static_hash()

        try:
            session['is_admin']
        except KeyError:
            session['is_admin'] = False

        return dict(static_hash=static_hash, app_id=app.config['APP_ID'], is_admin=session['is_admin'])

    if app.config['DEBUG']:
        from pony import orm
        from flask import send_from_directory

        orm.sql_debug(True)

        @app.route('/uploads/<path:path>')
        def uploads(path):
            return send_from_directory('uploads', path)

    return app
