import os
from textwrap import indent
from flask import Flask, redirect, render_template, session, request, url_for
from datetime import date

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

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 create_db import Card, Deck
from config import CONFIG


engine = create_engine(CONFIG['DB_CONNECTION'])
dbsessionmaker = sessionmaker(bind=engine)
dbsession = dbsessionmaker()

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )                                                                # = kaj naj tu piše?

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass


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

    @app.route('/deck/beta', methods=["GET", "POST"])
    def deck2():
        if request.method == 'POST':
            pass

        return render_template("deck/index.html")


    #@login_required
    @app.route('/deck/index', methods=["GET", "POST"])
    def deck():
        if not 'user_id' in session:
            return index()

        user_id = session['user_id']
        username = session['username']

        #pokliče na bazo, da dobi str card idjev, ga spremeni v list in srevira karte po idjih
        deck_query = dbsession.query(Deck).filter(Deck.owner_id == user_id)
        deck_object = deck_query.filter(Deck.completed == False).first()
        # @TODO: ce deck, ne obstaja, kaj naj zaj jas?

        deck_id = deck_object.id

        # Smo oddali obrazec?
        if request.method == 'POST':
            card_id = request.form.get('card_id', None)
            if not card_id:
                raise Exception("card_id je nujen!")


            submit_card = dbsession.query(Card).get(card_id)
            # @TODO preveri, ali je card del trenutnega decka!

            # Ali damo share? Potem nastavi na share in ponovi obrazec
            share = request.form.get("share", None)
            if share:
                print(share)
                # @TODO logika za share!

            # Če ne, gre za rate!
            else:
                rate = request.form.get('rate', None) #je to nevarno??
                print(rate)
                
                if not rate:
                    raise Exception("manjka rate info!")


                if rate == "Yes":
                    submit_card.interest_rate = 1
                
                elif rate == "Maybe":
                    k = 0.5
                    print(submit_card)
                    submit_card.interest_rate= abs(submit_card.interest_rate*k)
                    
                elif rate == "No":
                    k = 0.1
                    submit_card.interest_rate = abs(submit_card.interest_rate*k)

                # zaporedno število trenutnega carda v decku
                next_card = deck_object.current_card + 1

                # Ali je deck končan?
                if next_card >= deck_object.number_of_cards:
                    deck_object.completed = True
                    dbsession.commit()
                    return redirect(url_for("menu.index"))

                deck_object.current_card = next_card
                dbsession.commit()
            #dbsession.query(Card).filter(Card.id == card.id).update({'last_review': date()})
        
        # Loudamo naslednjo karto v decku
        show_card_index = deck_object.current_card
        show_card_id = deck_object.cards_by_id.split(",")[show_card_index]
        show_card = dbsession.query(Card).get(show_card_id)

        if not show_card:
            raise Exception("Ne najdem naslednje karte")

        # Prikaži obrazec
        return render_template("deck/index.html", username=username, card=show_card)
            
    
    @app.route("/share_button", methods=["GET", "POST"])
    def share_button():
        userid = session["user_id"]
        username = session["username"]
        card_number = session["card_number"]
    
        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.add_url_rule('/', endpoint='index')

    return app


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