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()