import werkzeug

werkzeug.cached_property = werkzeug.utils.cached_property
from os import environ
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_caching import Cache
from pymemcache import Client
from sqlalchemy import MetaData

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = environ['DATABASE_URL']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['CACHE_TYPE'] = 'MemcachedCache'
app.config['CACHE_MEMCACHED_SERVERS'] = Client("memcached.local")

metadata = MetaData()
db = SQLAlchemy(app, metadata=metadata)
cache = Cache(app)

try:
    from flask_migrate import Migrate

    migrate = Migrate(app=app, db=db)
except ImportError:
    Migrate = None
    print("To migrate install Flask-Migrate", flush=True)

try:
    if environ['BACKGROUND'] == "True":
        from Background.Task import MatchCreator, StudyGroupMatchCreator

        if not Migrate:
            MatchCreator.start()
            StudyGroupMatchCreator.start()
except KeyError:
    pass

import Blueprints

Blueprints.api.init_app(app)

from Blueprints.Gamification import game_blueprint

app.register_blueprint(game_blueprint)


# with app.app_context(), app.test_request_context():
#     print(Blueprints.api.__schema__)

@app.route('/')
def hello_world():
    return 'Hello World!'


@app.after_request
def after_request_func(response):
    db.session.close()
    return response
