from flask import Flask, redirect, render_template, session, request, url_for

from auth import login_required, bp as auth_bp
from deck import bp as deck_bp
from menu import bp as menu_bp
from upload import bp as upload_bp
from matches import bp as matches_bp
from settings import bp as settings_bp
from prob_session import prob_session

from config import CONFIG

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY=CONFIG['SECRET_KEY']
    )

    @app.route('/')
    @login_required
    def index():
        return 'redirecting' # meče skoz nazaj na login TODO

    # Ce je napaka baze, naredi rollback
    @app.errorhandler(500)
    def internal_error(error):
        session.rollback()
        return render_template('500.html'), 500

    @app.route('/deck', methods=["GET", "POST"])
    def deck():
        return prob_session()
    
    @app.route("/share_button", methods=["GET", "POST"])
    def share_button():   
        print("share!!!")
        return redirect(url_for("deck"))


    @app.route('/logout')
    def logout():
        session.pop("user_id", None)
        return index()


    @app.route('/match')
    def match():
        return "match"    
    

    #app.register_blueprint(bp) # ??
    app.register_blueprint(auth_bp)
    app.register_blueprint(deck_bp)
    app.register_blueprint(menu_bp)
    app.register_blueprint(upload_bp)
    app.register_blueprint(matches_bp)
    app.register_blueprint(settings_bp)
    app.add_url_rule('/', endpoint='index')

    return app


app = create_app()
app.run(debug=True, host="0.0.0.0")
