from app import app, db
from flask import render_template, redirect, url_for
from sqlalchemy.sql.expression import func
from app.models import Thing
from app.forms import NewForm


@app.route("/new", methods=["GET", "POST"])
def new():
    form = NewForm()
    if form.validate_on_submit():
        thing = Thing(description=form.description.data, descriptionL=form.descriptionL.data, theID=form.value.data)
        db.session.add(thing)
        db.session.commit()
        return redirect(url_for("new"))
    return render_template("new.html", form=form)


@app.route("/ranking")
def ranking():
    things = Thing.query.order_by(Thing.value.desc()).all()
    count = len(things)
    return render_template("ranking.html", things=things, count=count)


@app.route("/admin")
def admin():
    things = Thing.query.order_by(Thing.count.desc()).all()
    return render_template("admin.html", things=things)


@app.route("/faq")
def faq():
    things = Thing.query.order_by(Thing.value.desc()).all()
    count = len(things)
    return render_template("faq.html", count=count)


@app.route("/")
def index():
    while len(Thing.query.order_by(Thing.value.desc()).all()) < 2:
        print(f"creating dummy entry")
        thing = Thing(description="description", descriptionL="long description", theID=0)
        db.session.add(thing)
        db.session.commit()

    avg = db.session.query(func.avg(Thing.count)).first()[0]
    # print("AVG: ", avg)
    entries = []  # Thing.query.filter(Thing.count <= avg).order_by(func.random()).limit(2).all()
    while len(entries) != 2:  # catch out of bounds below.
        # print("Len not equal 2")
        entries = Thing.query.filter(Thing.count <= avg).order_by(func.random()).limit(2).all()
        avg = avg + 0.1

    for e in entries:
        # print("Count: ", e.count)
        e.choosen()
        db.session.add(e)
    db.session.commit()
    return render_template("index.html", left=entries[0],
                           right=entries[1])  # hopefully the out of bounds is caught above!


@app.route("/upvote/<id>")
def upvote(id):
    thing = Thing.query.get(id)
    thing.upvote()
    db.session.add(thing)
    db.session.commit()
    return redirect(url_for("index"))
