def login():
	if fl.request.method == "GET":
		if "user" in fl.session:
			return fl.redirect(fl.url_for("userpage"))
		else:
			return fl.render_template("login.html")
	elif fl.request.method == "POST":
		if fl.request.is_json:
			credentials = fl.request.get_json()
			userData = db.queryRead(
				"SELECT * FROM USERS WHERE username = :username",
				credentials
			)

			if len(userData) == 0:
				return fl.jsonify({"error": "Bad username."})
			else:
				userData = userData[0]

			if db.checkPassword(
				credentials["password"],
				userData["salt"], userData["hash"]
			):
				fl.session["user"] = credentials["username"]
				return fl.jsonify({"url": fl.url_for("userpage"), "error": "None"})
			else:
				return fl.jsonify({"error": "Bad password."})
		else:
			return fl.jsonify(noJSONError)
def getSheets(user):
	raw = db.queryRead(
		"SELECT * FROM SHEETS WHERE username = :user",
		{"user": user}
	)
	return [
		{"name": sheet["sheetname"], "link": sheet["path"].split(".json")[0][1:]}
		for sheet in raw
	]
def sendSheet(user, sheet):
	fl.after_this_request(noCaching)
	if "user" in fl.session:
		if user == fl.session["user"]:
			try:
				sheetPath = db.queryRead(
					"SELECT * FROM SHEETS " \
					+ "WHERE username = :user " \
					+ "AND sheetname = :sheet",
					{"user": user, "sheet": sheet}
				)[0]["path"]
				#print(sheetPath)
				print("\t[" + user + "]: Sending sheet " + sheet)
				return fl.send_from_directory("./sheets/" + user + '/', sheet + ".json")
			except IndexError:
				print("\t[" + user + "]: Sheet \"" + sheet + "\" does not exist")
				return fl.redirect(fl.url_for("userpage"))
		else:
			print("Incorrect user access for " + sheet)
			return fl.redirect(fl.url_for("userpage"))
	else:
		return fl.redirect(fl.url_for("login"))
def userpage():
	if fl.request.method == "GET":
		if "user" in fl.session:
			return fl.render_template(
				"userpage.html",
				user = fl.session["user"],
				sheets = getSheets(fl.session["user"])
			)
		else:
			return fl.redirect(fl.url_for("login"))
	elif fl.request.method == "POST":
		if not "user" in fl.session:
			return fl.redirect(fl.url_for("login"))
		elif fl.request.is_json:
			userRequest = fl.request.get_json()
			userRequest["user"] = fl.session["user"]
			if userRequest["method"] == "newSheet":
				if not strings.isAllowedChars(userRequest["newSheetName"]):
					return fl.jsonify({
						"error": "Outlawed characters detected in \"" \
						+ userRequest["newSheetName"] \
						+ "\". Please do not use quote marks or the backslash."
					})
				elif len(
					db.queryRead(
						"SELECT * FROM SHEETS " \
						+ "WHERE username = :user " \
						+ "AND sheetname = :newSheetName",
						userRequest
					)
				) != 0:
					return fl.jsonify({
						"error": "Sheet \"" + userRequest["newSheetName"] \
						+ "\" already exists. Please retry with a different name."
					})
				else:
					userRequest["path"] = "./sheets/" + userRequest["user"] + '/' \
						+ userRequest["newSheetName"] + ".json"

					if len(
						db.queryWrite(
							"INSERT INTO SHEETS VALUES " \
							+ "(:user, :newSheetName, :path)",
							userRequest
						)
					) == 0:
						newFile = open(userRequest["path"], 'w')
						json.dump(ds.defaultSheet, newFile, indent = 4, sort_keys = True)
						newFile.close()

						return fl.jsonify({
							"error": "None.",
							"url": userRequest["path"],
							"newSheetName": userRequest["newSheetName"]
						})
					else:
						return fl.jsonify({
							"error": SQL_WRITE_ERROR,
						})

			elif userRequest["method"] == "delete":
				if len(
					db.queryWrite(
						"DELETE FROM SHEETS " \
						+ "WHERE sheetname = :sheetName",
						userRequest
					)
				) == 0:
					if not os.path.exists("./recycleBin/"):
						os.mkdir("./recycleBin/")
					if not os.path.exists(
						"./recycleBin/" + userRequest["user"] + '/'
					):
						os.mkdir("./recycleBin/" + userRequest["user"] + '/')

					os.rename(
						"./sheets/" + userRequest["user"] + '/' \
						+ userRequest["sheetName"] + ".json",
						"./recycleBin/" + userRequest["user"] + '/' \
						+ userRequest["sheetName"] + '.' \
						+ str(time.time_ns()) + ".json"
					)
					return fl.jsonify({
						"error": "None.",
						"sheetName": userRequest["sheetName"]
					})
				else:
					return fl.jsonify({"error": SQL_WRITE_ERROR})

			elif userRequest["method"] == "duplicate":
				if len(
					db.queryRead(
						"SELECT * FROM SHEETS " \
						+ "WHERE sheetname = :duplicateName",
						userRequest
					)
				) != 0:
					return fl.jsonify(
						{
							"error": "Duplicate name \"" \
							+ userRequest["duplicateName"] \
							+ "\" already in use. Please try again."
						}
					)
				else:
					userRequest["originalPath"] = "./sheets/" + userRequest["user"] \
						+ '/' + userRequest["sheetName"] + ".json"
					userRequest["duplicatePath"] = "./sheets/" + userRequest["user"] \
						+ '/' + userRequest["duplicateName"] + ".json"

				if len(
					db.queryWrite(
						"INSERT INTO SHEETS VALUES " \
						+ "(:user, :duplicateName, :duplicatePath)",
						userRequest
					)
				) != 0:
					return fl.jsonify({"error": SQL_WRITE_ERROR})
				else:
					shutil.copyfile(
						userRequest["originalPath"],
						userRequest["duplicatePath"]
					)
					return fl.jsonify({
						"error": "None.",
						"sheetName": userRequest["sheetName"],
						"duplicateName": userRequest["duplicateName"]
					})

			else:
				return fl.jsonify({"error": "Bad POST Request."})
		else:
			return fl.jsonify(noJSONError)
		fl.redirect("/static/" + script)

def getSheets(user):
	raw = db.queryRead(
		"SELECT * FROM SHEETS WHERE username = :user",
		{"user": user}
	)
	return [
		{"name": sheet["sheetname"], "link": sheet["path"].split(".json")[0][1:]}
		for sheet in raw
	]

sheetQuery = "SELECT * FROM SHEETS WHERE username = :user AND sheetname = :sheet"

checkDBForSheet = lambda user, sheet : sheet == db.queryRead(
	sheetQuery,	{"user": user, "sheet": sheet}
)[0]["sheetname"]

getSheetPath = lambda user, sheet : db.queryRead(
	sheetQuery, {"user": user, "sheet": sheet}
)[0]["path"]

def loadSheet(user, sheet):
	if "user" in fl.session:
		if user == fl.session["user"]:
			try:
				if checkDBForSheet(user, sheet):
					return fl.render_template(
						"sheet.html",
						sheetName = sheet,
						username = fl.session["user"],