from flask import Flask, request, session, redirect
import sqlite3
import time

app = Flask(__name__)
app.secret_key = "irgendein-geheimer-text-9009"

def get_db():
    db = sqlite3.connect("adventure.db")
    db.row_factory = sqlite3.Row   # Spalten per Name ansprechen
    return db

@app.route("/", methods=["GET", "POST"])
def start():
    if request.method == "POST":
        name = request.form["name"].strip()
        db = get_db()
        cur = db.execute(
            "INSERT INTO spieler (name, start_zeit) VALUES (?, ?)",
            (name, time.time())
        )
        db.commit()
        session["spieler_id"] = cur.lastrowid
        db.close()
        return redirect("/app/raum/1")

    return '<h1>Verlies</h1>' \
         + '<form method="post">Dein Name: <input name="name"><button>Start</button></form>'

@app.route("/raum/<int:id>", methods=["GET", "POST"])
def raum(id):
    db = get_db()
    r = db.execute("SELECT * FROM raeume WHERE id=?", (id,)).fetchone()

    if r["raetsel_frage"]:                    # Rätselraum?
        if request.method == "POST":
            if request.form["antwort"].strip() == r["raetsel_antwort"]:
                db.close()
                return "<h1>Befreit!</h1>"
            db.close()
            return 'Leider falsch. <a href="/app/raum/' + str(id) + '">nochmal</a>'
        db.close()
        return "<h1>" + r["name"] + "</h1><p>" + r["beschreibung"] + "</p>" \
             + '<form method="post">' + r["raetsel_frage"] \
             + ' <input name="antwort"><button>OK</button></form>'

    ausgaenge = db.execute(
        "SELECT richtung, nach_raum FROM ausgaenge WHERE von_raum=?", (id,)
    ).fetchall()
    db.close()

    html = "<h1>" + r["name"] + "</h1>"
    html = html + "<p>" + r["beschreibung"] + "</p>"
    for a in ausgaenge:
        html = html + '<a href="/app/raum/' + str(a["nach_raum"]) + '">' \
                    + a["richtung"] + '</a> &nbsp; '
    return html

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9009)