import pymongo
from flask import Flask, request, render_template, redirect, url_for, abort

# initialize connection to database
app = Flask(__name__)
config = {
	"username": "admin",
	"password": "pass",
	"server": "localhost:27017",
}
connector = "mongodb://{}:{}@{}".format(config["username"],config["password"], config["server"])
client = pymongo.MongoClient(connector)
db = client["groclist"]

@app.route("/")
def main():
	return render_template("index.html")

@app.route("/login", methods=["GET","POST"])
def login():
	error = None
	if request.method == "POST":
		username = request.form["username"]
		password = request.form["password"]
		if db.user_cred.find_one({"username": username, "password": password}):
			auth_user_id = db.user_cred.find_one({"username": username},{"uuid": 1})
			if auth_user_id:
				app.logger.info(auth_user_id)
				return redirect(url_for("list", id=auth_user_id["uuid"]))
				#return render_template("list.html", username=username)
			else:
				return redirect(url_for("not_found"))
		else:
			error = "Usernaam of wachtwoord onbekend, probeer opnieuw"
	return render_template("login.html", error=error)

@app.route("/list/<id>", methods=['GET'])
def list(id):
	return render_template("list.html", id=id)

@app.errorhandler(404)
def not_found(error):
	app.logger.info(error)
	return render_template("404.html"), 404

# start server with run method
if __name__ == "__main__":
	app.run(debug=True)
