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

app = Flask(__name__)
myclient = pymongo.MongoClient("mongodb://admin:pass@localhost:27017")
mydb = myclient["groclist_db"]
mycol_users = mydb["groclist_users"]
username=""

@app.route("/", methods=['GET', 'POST'])
def groclist_home():
	error = None
	if request.method == 'POST':
		if request.form.get('login') == 'Inloggen':
			return redirect(url_for('groclist_login'))
	elif request.method == 'GET':
		return render_template('index.html')

	return render_template('index.html',error=error)

@app.route("/login", methods=['GET', 'POST'])
def groclist_login():
	error = None
	if request.method == 'POST':
		username = request.form['username']
		password = request.form['password']
		if mycol_users.find_one({"username": username, "password": password}):
			return redirect(url_for('groclist_welcome'))
		else:
			error = 'Username of wachtwoord onbekend. Probeer opnieuw'

	return render_template("login.html", error=error)

@app.route("/welcome", methods=['GET', 'POST'])
def groclist_welcome():
	if request.method == 'GET':
		userid = mycol_users.find_one({"username": username}, {"_id": 1})
		print(userid)
		return render_template("welcome.html", userid=userid)
	else:
		error = "Userid is niet bekend. Database defect"
		return render_template("index.html", error=error)

app.add_url_rule("/welcome", "welcome", groclist_welcome)  

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