# Copyright (c) 2015, Xhive Global Ltd. and Contributors
# License: MIT. See LICENSE

from urllib.parse import parse_qsl

import xhiveframework
from xhiveframework import _
from xhiveframework.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 = xhiveframework.local.request.query_string
	query = dict(parse_qsl(query_string))
	query = {key.decode(): val.decode() for key, val in query.items()}
	if not "k" in list(query):
		xhiveframework.throw(_("Not Permitted"), xhiveframework.PermissionError)
	query = (query["k"]).strip()
	if False in [i.isalpha() or i.isdigit() for i in query]:
		xhiveframework.throw(_("Not Permitted"), xhiveframework.PermissionError)
	return query


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