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

import xhiveframework


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

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


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

	xhiveframework.response.docs.append(doc)


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

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

	if not xhiveframework.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
