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

app = Flask(__name__)


@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("/welcome")
def groclist_welcome():
	return render_template("welcome.html")

@app.route("/login", methods=['GET', 'POST'])
def groclist_login():
	error = None
	if request.method == 'POST':
		myclient = pymongo.MongoClient("mongodb://admin:pass@localhost:27017")
		mydb = myclient["groclist_db"]
		mycol = mydb["groclist_users"]
		username = request.form['username']
		password = request.form['password']
		name = ""
		if mycol.find_one({"username": username, "password": password}):
			# for user_info in mycol.find({}, {"name": 0}):
			#	print("Welkom", user_info)
			return redirect(url_for('groclist_welcome'))
		else:
			error = 'Username of wachtwoord onbekend. Probeer opnieuw'

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


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

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