# Copyright (c) 2015, InfluxFramework LLC
# License: MIT. See LICENSE

import influxframework
from influxframework.translate import send_translations


@influxframework.whitelist()
def get(name):
	"""
	Return the :term:`doclist` of the `Page` specified by `name`
	"""
	page = influxframework.get_doc("Page", name)
	if page.is_permitted():
		page.load_assets()
		docs = influxframework._dict(page.as_dict())
		if getattr(page, "_dynamic_page", None):
			docs["_dynamic_page"] = 1

		return docs
	else:
		influxframework.response["403"] = 1
		raise influxframework.PermissionError("No read permission for Page %s" % (page.title or name))


@influxframework.whitelist(allow_guest=True)
def getpage():
	"""
	Load the page from `influxframework.form` and send it via `influxframework.response`
	"""
	page = influxframework.form_dict.get("name")
	doc = get(page)

	# load translations
	if influxframework.lang != "en":
		send_translations(influxframework.get_lang_dict("page", page))

	influxframework.response.docs.append(doc)


def has_permission(page):
	if influxframework.session.user == "Administrator" or "System Manager" in influxframework.get_roles():
		return True

	page_roles = [d.role for d in page.get("roles")]
	if page_roles:
		if influxframework.session.user == "Guest" and "Guest" not in page_roles:
			return False
		elif not set(page_roles).intersection(set(influxframework.get_roles())):
			# check if roles match
			return False

	if not influxframework.has_permission("Page", ptype="read", doc=page):
		# check if there are any user_permissions
		return False
	else:
		# hack for home pages! if no Has Roles, allow everyone to see!
		return True
