"""
A custom renderer to produce DOI landing pages.

In principle, this is just an application of an XSLT style sheet;
perhaps we should teach the qp renderer whatever is necessary so
it can do this?
"""

from lxml import etree as lxmletree

from gavo import api
from gavo import web
from gavo.formal import nevowc

class LandingPage(nevowc.TemplatedPage):
	"""a DOI landing page.

	This is constructed with a (scheme-less) DOI.
	"""
	def __init__(self, doi):
		self.doi = doi
		nevowc.TemplatedPage.__init__(self)

	def render(self, request):
		with api.getTableConn() as conn:
			res = list(conn.query("select full_record from voidoi.dois"
				" where doi=%(doi)s",
				{"doi": self.doi}))
			if len(res)==0:
				raise api.UnknownURI("The DOI %s is unknown here."%self.doi)
		return str(STYLESHEET(lxmletree.XML(res[0][0]))).encode("utf-8")


class MainPage(web.ServiceBasedPage):
	"""this main page expects at least two segments; the first is interpreted
	as the prefix, the others as the local parts.
	"""

	name = "custom"

	@classmethod
	def isBrowseable(self, service):
		return False

	def render(self, request):
		raise api.UnknownURI("You need to specify valid DOI prefix/local part"
			" in the path")

	def getChild(self, name, request):
		if name==b"":
			return self
		return LandingPage("/".join(request.popSegments(name)))


def initModule(**kwargs):
	global STYLESHEET
	with open(RD.getAbsPath("res/vor-to-landing.xslt")) as f:
		STYLESHEET = lxmletree.XSLT(lxmletree.parse(f))
