from flask import (
    Blueprint, redirect, render_template, request, session, url_for
)
from create_db import Card, get_session, get_engine
from sr_session import schedule_status, remaining_items, list_of_due_cards_by_ids, list_of_new_cards_by_ids, rated_today_by_staus
from settings import get_settings
from auth import login

bp = Blueprint('menu', __name__, url_prefix='/menu')

@bp.route("/", methods=("GET", "POST"))
def index():

    if 'user_id' not in session:
        return login()
    
    if 'user_id' in session:
        user_id = session['user_id']
        username = session['username']
        status = schedule_status(user_id)

        user_settings = get_settings(user_id)
        max_new = int(user_settings["max_new"])
        max_due = int(user_settings["max_due"])

        total_new = len(list_of_new_cards_by_ids(user_id))
        total_due = len(list_of_due_cards_by_ids(user_id))
        rated_today_new = rated_today_by_staus("new", user_id)
        rated_today_due = rated_today_by_staus("due", user_id)
        remaining_new_today = remaining_items(max_new, total_new, rated_today_new)
        remaining_due_today = remaining_items(max_due, total_due, rated_today_due)

        if request.method == "POST":
            action = request.form.get("menu", False) #internetna rešitev, nevem kako, ampak dela, tj. dobi info iz meni buttonov
            if action == "new_session":
                #preverimo če so sploh karte v collectionu
                Session = get_session()
                with Session() as dbsession:
                    c = dbsession.query(Card).filter(Card.owner_id == user_id).all()
                    if c == []:
                        dbsession.close()
                        return render_template("error/no_cards_in_collection.html", username=username)
                    dbsession.close()
                    
                get_engine().dispose()
                return redirect(url_for("deck"))
            

            elif action == "matches":
                return redirect(url_for("matches.index"))
            elif action == "upload":
                return redirect(url_for("upload.index"))
            elif action == "import-link":
                return redirect(url_for("import_link.index"))
            elif action == "settings":
                settings = get_settings(user_id)
                return render_template("settings.html", username=username, user_id=user_id, settings=settings)
            elif action == "instructions":
                return render_template("instructions.html", username=username, user_id=user_id)

    return render_template("menu.html", username=username, deck_status=status, remaining_due=remaining_due_today, remaining_new=remaining_new_today)
