"""
A core that spits out utypes for STC-S
"""

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



def stringify(v):
	if isinstance(v, stc.ColRef):
		return "*(%s)"%v
	return str(v)


def _parseSTCX(inputString):
	return stc.parseSTCX(inputString)[0][1]


def _parseUtypes(inputString):
	return stc.parseFromUtypes([l.split() for l in inputString.split("\n")
		if l.strip()])


def _formatSTCX(ast):
	return "text/xml", stc.getSTCXProfile(ast)

def _formatSTCS(ast):
	return "text/plain", stc.getSTCS(ast)

def _formatUtypes(ast):
	return ("text/plain",
		utils.formatSimpleTable([(utype, stringify(value))
			for utype, value in stc.getUtypes(ast)]))


class Core(core.Core):

	inputTableXML = """
		<inputTable>
			<inputKey name="inString" tablehead="Input string"
				type="text" required="True"
				widgetFactory="widgetFactory(ScalingTextArea, rows=5)"
				description="A string containing the input in the format
					defined by inputFormat.  See the Service Info for examples."/>

			<inputKey name="inputFormat" tablehead="Input format"
					type="text" description="Source format of the STC information"
					multiplicity="single">
				<values default="STC-S">
					<option>STC-S</option>
					<option>utypes</option>
					<option>STC-X</option>
				</values>
			</inputKey>

			<inputKey name="outputFormat" tablehead="Output format"
					type="text" description="Target format of the STC information"
					multiplicity="single">
				<values default="utypes">
					<option>utypes</option>
					<option>STC-X</option>
					<option>STC-S</option>
				</values>
			</inputKey>
		</inputTable>
		"""
	outputTableXML = """
		<outputTable/>
		"""

	_parsers = {
		"STC-S": stc.parseQSTCS,
		"STC-X": _parseSTCX,
		"utypes": _parseUtypes,
	}

	_formatters = {
		"STC-S": _formatSTCS,
		"STC-X": _formatSTCX,
		"utypes": _formatUtypes,
	}

	def run(self, service, inputTable, queryMeta):
		parser = self._parsers[inputTable.getParam("inputFormat")]
		try:
			ast = parser(inputTable.getParam("inString"))
		except Exception as msg:
			raise base.ValidationError("Invalid STC-S: %s"%str(msg),
				"inString")
		formatter = self._formatters[inputTable.getParam("outputFormat")]
		return formatter(ast)
