"""
A core running the XSL transformation for datalinks that DaCHS has
built in.
"""

import functools

from lxml import etree as lxmletree

from gavo import base
from gavo import utils
from gavo.svcs import core


@functools.lru_cache(1)
def getXSLT():
		with base.openDistFile("web/xsl/datalink-to-html.xsl", "rb") as f:
			return lxmletree.XSLT(
				lxmletree.XML(f.read()))


def _doDatalinkXSLT(data):
	"""returns data transformed with the datalink-to-html XSLT.
	"""
	try:
		tree = lxmletree.XML(data)
	except lxmletree.XMLSyntaxError as ex:
		raise base.ValidationError(
			"Parse error in your XML: {}".format(ex),
			"dluri")
			
	return bytes(getXSLT()(tree))


class Core(core.Core):
	def run(self, service, inputTable, queryMeta):
		uri = inputTable.getParam("dluri")
		if uri:
			with utils.urlopenRemote(uri) as f:
				dlxml = f.read()

		elif inputTable.getParam("in_data"):
			dlxml = inputTable.getParam("in_data")[1].read()

		else:
			raise base.ValidationError("Need either URI or upload", "dluri")

		return ("text/html", _doDatalinkXSLT(dlxml))
