from flask import Flask,render_template,session,request,redirect
import json
import random
import json

app = Flask(__name__)
app.secret_key = str(random.randint(0,10000000000))

@app.route("/",methods=['GET','POST'])
def index():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        with open("accounts.json") as file:
            data = json.load(file)
            accounts = data["accounts"]
            
            for account in accounts:
                if account["username"] == username and account["password"] == password:
                    session['username'] = username
                    return redirect("/")
        
        return render_template("error.html", error="Invalid credentials")
    else:
        if 'username' in session:
            if session['username'] == "rschiopu":
                return redirect("/admin")
            else:
                return render_template("index.html")
        else:
            return render_template("login.html")

@app.route("/logout")
def logout():
    session.clear()
    return redirect("/")

@app.route("/admin")
def admin():
    if 'username' in session:
        if session['username'] == "rschiopu":
            playtests = json.load(open("playtests.json"))
            return render_template("admin.html",playtests=playtests)
    else:
        return redirect("/")

@app.route("/admin/createplaytest",methods=['POST','GET'])
def createplaytest():
    try:
        if session['username'] != "rschiopu":
            return render_template("error.html",error="Forbidden.")
    except:
        return render_template("error.html",error="Unauthorized.")
    if request.method == 'POST':
        playtests = json.load(open("playtests.json"))
        playtest_id = str(random.randint(111111,999999))
        duration = request.form['duration']
        message = request.form['message']
        playtests[playtest_id] = {"duration":duration,"message":message,"active":True}
        with open("playtests.json", "w") as file:
            json.dump(playtests, file)
        return render_template("admin.html",playtest_id=playtest_id)
    else:
        return render_template("createplaytest.html")


@app.route("/playtest/<string:playtest_id>")
def playtest(playtest_id):
    playtests = json.load(open("playtests.json"))
    if playtest_id in playtests:
        if playtests[playtest_id]["active"]:
            return render_template("playtest.html",duration=playtests[playtest_id]["duration"],message=playtests[playtest_id]["message"],playtest_id=playtest_id)
        else:
            return render_template("error.html",error="Playtest is not active. Contact a developer if you think this is a mistake.")
    else:
        return render_template("error.html",error="Playtest does not exist.")
    
@app.route("/playtest/<string:playtest_id>/submit",methods=['POST','GET'])
def submit(playtest_id):
    if request.method == 'POST':
        playtests = json.load(open("playtests.json"))
        if playtest_id in playtests:
            feedback = request.form['feedback']
            playtests[playtest_id]["feedback"] = feedback
            playtests[playtest_id]["active"] = False
            with open("playtests.json", "w") as file:
                json.dump(playtests, file)
            
            return "<h1 style='font-family:sans-serif;'>Thank you for your feedback!</h1>"
        else:
            return render_template("error.html",error="Playtest does not exist.")
    else:
        playtests = json.load(open("playtests.json"))
        if playtest_id in playtests:
            playtests[playtest_id]["active"] = False
            with open("playtests.json", "w") as file:
                json.dump(playtests, file)
            
            return "200 OK"
        else:
            return render_template("error.html",error="Playtest does not exist.")

@app.route("/playtest/<string:playtest_id>/isactive")
def isactive(playtest_id):
    playtests = json.load(open("playtests.json"))
    if playtest_id in playtests:
        return str(playtests[playtest_id]["active"])
    else:
        return render_template("error.html",error="Playtest does not exist.")

@app.route("/resetplaytests")
def resetplaytests():
    try:
        if session['username'] != "rschiopu":
            return render_template("error.html",error="Forbidden.")
    except:
        return render_template("error.html",error="Unauthorized.")
    with open("playtests.json", "w") as file:
        json.dump({}, file)
    return redirect("/admin")

@app.route("/playtest/<string:playtest_id>/updateduration/<string:duration>")
def updateduration(playtest_id,duration):
    playtests = json.load(open("playtests.json"))
    if playtest_id in playtests:
        playtests[playtest_id]["duration"] = duration
        with open("playtests.json", "w") as file:
            json.dump(playtests, file)
        return "200 OK"
    else:
        return render_template("error.html",error="Playtest does not exist.")

if __name__ == '__main__':
    app.run(host="0.0.0.0")