# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE

from urllib.parse import parse_qsl

import jingrow
from jingrow import _
from jingrow.twofactor import get_qr_svg_code


def get_context(context):
	context.no_cache = 1
	context.qr_code_user, context.qrcode_svg = get_user_svg_from_cache()


def get_query_key():
	"""Return query string arg."""
	query_string = jingrow.local.request.query_string
	query = dict(parse_qsl(query_string))
	query = {key.decode(): val.decode() for key, val in query.items()}
	if "k" not in list(query):
		jingrow.throw(_("Not Permitted"), jingrow.PermissionError)
	query = (query["k"]).strip()
	if False in [i.isalpha() or i.isdigit() for i in query]:
		jingrow.throw(_("Not Permitted"), jingrow.PermissionError)
	return query


def get_user_svg_from_cache():
	"""Get User and SVG code from cache."""
	key = get_query_key()
	totp_uri = jingrow.cache.get_value(f"{key}_uri")
	user = jingrow.cache.get_value(f"{key}_user")
	if not totp_uri or not user:
		jingrow.throw(_("Page has expired!"), jingrow.PermissionError)
	if not jingrow.db.exists("User", user):
		jingrow.throw(_("Not Permitted"), jingrow.PermissionError)
	user = jingrow.get_pg("User", user)
	svg = get_qr_svg_code(totp_uri)
	return (user, svg.decode())
