<?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:filter="Filter" xmlns:xs="http://www.w3.org/2001/XMLSchema"
	xmlns:n2="urn:hl7-org:v2xml"
	xmlns:fn="http://www.w3.org/2005/xpath-functions"
	exclude-result-prefixes="fn n2 xs xsi xsl">
	<xsl:output method="xml" encoding="UTF-8" indent="yes" />
	<xsl:template match="/n2:QRY_Q01">
		<filter:filter vhimVersion="Vhim_4_00">
			<filterId>CHDR_LAB_SINGLE_PATIENT_FILTER</filterId>
			<patients>
				<NationalId>
					<xsl:sequence select="xs:string(n2:QPD/n2:QPD.3)" />
				</NationalId>
				<excludeIdentifiers>
					<assigningAuthority>USDOD</assigningAuthority>
					<assigningFacility>200HD</assigningFacility>
				</excludeIdentifiers>
				<excludeIdentifiers>
					<assigningAuthority>USDOD</assigningAuthority>
					<assigningFacility>200CH</assigningFacility>
				</excludeIdentifiers>
				<excludeIdentifiers>
					<assigningAuthority>USVHA</assigningAuthority>
					<assigningFacility>200HD</assigningFacility>
				</excludeIdentifiers>
				<excludeIdentifiers>
					<assigningAuthority>USVHA</assigningAuthority>
					<assigningFacility>200CH</assigningFacility>
				</excludeIdentifiers>
			</patients>
			<entryPointFilter queryName="CHDR_LAB_QUERY">
            	<domainEntryPoint>LabTestPromise</domainEntryPoint>
                <xsl:variable name="rawStartDate" select="xs:string(n2:QPD/n2:QPD.5)"/>
            	<xsl:if test="string-length($rawStartDate) &gt;= 8">
	                <startDate>
						<xsl:call-template name="formatFilterDate">
							<xsl:with-param name="unformattedDate" select="$rawStartDate"/>
						</xsl:call-template>
					</startDate>
				</xsl:if>
				<xsl:variable name="rawStopDate" select="xs:string(n2:QPD/n2:QPD.6)"/>
            	<xsl:if test="string-length($rawStopDate) &gt;= 8">
					<endDate>
						<xsl:call-template name="formatFilterDate">
							<xsl:with-param name="unformattedDate" select="$rawStopDate"/>
						</xsl:call-template>
					</endDate>
				</xsl:if>
            </entryPointFilter>
		</filter:filter>
	</xsl:template>

	<xsl:template name="formatFilterDate">
		<xsl:param name="unformattedDate"/>
		<xsl:variable name="tempYearMonthDate"
			as="xs:string"
			select="substring($unformattedDate, 1 ,9)" />
		<xsl:variable name="tempYear"
			as="xs:string"
			select="substring($tempYearMonthDate,1,4)" />
		<xsl:variable name="tempMonth"
			as="xs:string" select="substring($tempYearMonthDate,5,2)" />
		<xsl:variable name="tempDay"
			as="xs:string" select="substring($tempYearMonthDate,7,2)" />
		<xsl:sequence
			select="concat($tempYear,'-',$tempMonth,'-',$tempDay)" />
	</xsl:template>
</xsl:stylesheet>
