<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" 
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:results="Results" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
	xmlns:fn="http://www.w3.org/2005/xpath-functions"
	xmlns:map="map:java.util.Map" 
	xmlns:clinicaldata="Clinicaldata"
	exclude-result-prefixes="fn xs xsi xsl map results clinicaldata">
	<xsl:output method="text" encoding="UTF-8" omit-xml-declaration="yes"/>
	
	<xsl:param name="status"/>
	<xsl:param name="uId"/>
	<xsl:param name="requestId"/>
	<xsl:param name="colType"/>
	<xsl:param name="patId"/>
		
	<xsl:template match="/clinicaldata:ClinicalData">{"pgdCreateResponse":{
		"status":"<xsl:value-of select="$status"/>",
		"uniqueId":"<xsl:value-of select="$uId"/>",
		"requestId":"<xsl:value-of select="$requestId"/>",
		"collectionType":"<xsl:value-of select="$colType"/>",
		"patientIdentity":"<xsl:value-of select="$patId"/>"<xsl:if test="count(./errorSection) = 1">,
		</xsl:if>
		<xsl:if test="count(./errorSection/errors/error) + count(./errorSection/fatalErrors/fatalError) + count(./errorSection/warnings/warning) &gt; 0">
			<xsl:call-template name="errorSectionTemplate"/>
		</xsl:if>}
	}
	</xsl:template>
	
	<xsl:template name="errorSectionTemplate">"errorSection":{
			<xsl:if test="count(./errorSection/errors/error) >= 1">"errors":{
				<xsl:for-each select="./errorSection/errors/error">"error":{
					<xsl:call-template name="exceptionTemplate"/>}<xsl:if test="position() != last()">,</xsl:if>
				</xsl:for-each>}<xsl:if test="count(./errorSection/fatalErrors/fatalError) + count(./errorSection/warnings/warning) &gt; 0">,</xsl:if>
			</xsl:if>
			<xsl:if test="count(./errorSection/fatalErrors/fatalError) >= 1">"fatalErrors":{
				<xsl:for-each select="./errorSection/fatalErrors/fatalError">"fatalError":{
					<xsl:call-template name="exceptionTemplate"/>}<xsl:if test="position() != last()">,</xsl:if>
				</xsl:for-each>}<xsl:if test="count(./errorSection/warnings/warning) &gt; 0">,</xsl:if>
			</xsl:if>
			<xsl:if test="count(./errorSection/warnings/warning) >= 1">"warnings":{
				<xsl:for-each select="./errorSection/warnings/warning">"warning":{
					<xsl:call-template name="exceptionTemplate"/>}<xsl:if test="position() != last()">,</xsl:if>
				</xsl:for-each>
			</xsl:if>}
	</xsl:template>	
	
	<xsl:template name="exceptionTemplate">
		"exceptionMessage":"<xsl:value-of select="exceptionMessage"/>",
		"displayMessage":"<xsl:value-of select="displayMessage"/>",
		"exception":"<xsl:value-of select="exception"/>",
		"errorCode":"<xsl:value-of select="errorCode"/>",
		"errorId":"<xsl:value-of select="errorId"/>"
	</xsl:template>
	
</xsl:stylesheet>