<?xml version="1.0" encoding="utf-8"?>
<!--

Copyright (c) 2002,2003 Regenstrief Institute, Inc.  All rights reserved.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

Written by Gunther Schadow.

$Id: spextract-titles.xsl,v 1.1.1.1 2005/02/17 00:43:51 gschadow Exp $

-->
<xsl:transform version="1.0"
   xmlns:saxon="http://saxon.sf.net/"
   xmlns:xwsf="java:net.sf.xwsf.saxon.Functions"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:ex="http://xwsf.sf.net/net.sf.xwsf.saxon.ExceptionElementFactory"
   xmlns:exd="http://xwsf.sf.net/exception"
   xmlns:rs="java:java.sql.ResultSet"
   xmlns:sys="java:java.lang.System"
   xmlns:gut="http://aurora.regenstrief.org/XML/GenericUpTranslator"
   extension-element-prefixes="saxon ex sys"
   exclude-result-prefixes="saxon ex rs exd sys gut xwsf">
<!-- spextract-report

 Load spextract reports from the SPEXTRACT_WORK table.

-->

  <xsl:import href="exception.xsl"/>
  <xsl:import href="db-common.xsl"/>
 
  <xsl:output method="xml" 
	      indent="yes" 
	      encoding="UTF-8"
	      media-type="text/xml"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="debug" select="0"/>
  <xsl:param name="schema" select="'RMRS.'"/>

  <xsl:param name="reportSQL">
     SELECT --+FIRST_ROWS
       RESULT_XML,
       INSTITUTION_ID,
       SERVICE_CODE,
       SERVICE_SYS_ID,    
       PHYSIOLOGIC_TIME
     FROM SPEXTRACT_WORK
       INNER JOIN <xsl:value-of select="$schema"/>MULTIMEDIA_CONTENT
         USING(INSTITUTION_ID, MULTIMEDIA_CONTENT_ID)
       INNER JOIN (
         SELECT MEDICAL_ORDER_ID,
                PATIENT_ID,
                SERVICE_CODE,
                SERVICE_SYS_ID,
                PHYSIOLOGIC_TIME
           FROM <xsl:value-of select="$schema"/>MEDICAL_ORDER
       ) USING(MEDICAL_ORDER_ID)
     WHERE STATUS='FINISHED'
  </xsl:param>

  <xsl:template match="/">
    <dataload-transcript>
      <ex:try atomic="no">
        <xsl:apply-templates select="node()"/>

	<ex:catch exception="java.lang.Throwable">
	  <xsl:message terminate="yes">
	    <xsl:call-template name="exd:dump">
	      <xsl:with-param name="name" select="'ERROR'"/>
	    </xsl:call-template>
	  </xsl:message>
	</ex:catch>
        <ex:finally>
          <xsl:sequence xmlns:c="java:java.sql.Connection"
                        select="c:close($connection)"/>
        </ex:finally>
      </ex:try>  
    </dataload-transcript>
  </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:apply-templates select="@*|node()"/>
  </xsl:template>

  <xsl:template match="report-batch[@url]">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="report">
    <xsl:param name="whereClause">
      <xsl:apply-templates mode="makeWhereClause" select="@*|node()"/>
    </xsl:param>
    <xsl:choose>
      <xsl:when test="$whereClause">
        <xsl:apply-templates mode="sqlselect" select=".">
          <xsl:with-param name="whereClause" select="$whereClause"/>
        </xsl:apply-templates>
      </xsl:when>
      <xsl:otherwise>
        <xsl:apply-templates mode="sqlselect" select="."/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template mode="sqlselect" match="report">
    <xsl:param name="schema" select="ancestor-or-self::*/@schema[1]"/>
    <xsl:param name="whereClause" select="''"/>
    <xsl:if test="$debug > 1">
      <xsl:message>
	<reportSQL>
          <xsl:value-of select="concat($reportSQL,$whereClause)"/>
	</reportSQL>
      </xsl:message>
    </xsl:if>
    <xsl:variable name="rset"
       xmlns:cn="java:java.sql.Connection"
       xmlns:st="java:java.sql.Statement"
       select="st:executeQuery(cn:createStatement($connection), 
                     concat($reportSQL,' ',$whereClause))"/>

    <saxon:while test="rs:next($rset)">
      <ex:try atomic="yes">
	  <xsl:variable name="textString">
	    <xsl:choose>
	      <xsl:when test="ancestor-or-self::report-batch/@use-clob='no'">
		<xsl:value-of 
		   select="rs:getString($rset,'RESULT_XML')"/>
	      </xsl:when>
	      <xsl:otherwise>
		<xsl:variable name="textClob"
		   select="rs:getClob($rset,'RESULT_XML')"/>       
		<xsl:value-of xmlns:clob="java:java.sql.Clob"
		   select="clob:getSubString($textClob,1,
					     clob:length($textClob))"/>
	      </xsl:otherwise>
	    </xsl:choose>
	  </xsl:variable>
	  <xsl:variable name="text" select="saxon:parse($textString)"/>

          <xsl:variable name="institutionId" 
	    select="rs:getLong($rset,'INSTITUTION_ID')"/>
	  <xsl:variable name="serviceCode" 
	    select="rs:getLong($rset,'SERVICE_CODE')"/>
	  <xsl:variable name="serviceSystem" 
	    select="rs:getLong($rset,'SERVICE_SYS_ID')"/>

	  <xsl:for-each select="$text/spextract">
	    <xsl:copy>
	      <xsl:attribute name="institutionId">
	        <xsl:value-of select="$institutionId"/>
	      </xsl:attribute>
	      <xsl:sequence select="@serviceCode"/>
	      <xsl:sequence select="@physiologicTime"/>
	      <serviceCode code="{$serviceCode}" 
	                   codeSystem="{$serviceSystem}"/>
	      <xsl:for-each select="//section">
	        <xsl:copy>
		  <xsl:sequence select="@*"/>
		</xsl:copy>
	      </xsl:for-each>
	    </xsl:copy>
	  </xsl:for-each>

	  <ex:catch exception="java.lang.Throwable">
            <xsl:call-template name="exd:dump">
	      <xsl:with-param name="name" select="exception"/>
	    </xsl:call-template>
	  </ex:catch>
      </ex:try>
    </saxon:while>
  </xsl:template>

<!-- MODE: makeWhereClause -->

<xsl:template mode="makeWhereClause" match="report/@id">
  <xsl:text> AND MULTIMEDIA_CONTENT_ID >= </xsl:text>
  <xsl:value-of select="."/>
</xsl:template>

<xsl:template mode="makeWhereClause" match="report/@code">
  <xsl:text> AND ( SERVICE_SYS_ID=1 AND SERVICE_CODE IN (''</xsl:text>
  <xsl:for-each select="tokenize(., '\s+')">
     <xsl:text>, '</xsl:text>
     <xsl:value-of select="."/>
     <xsl:text>'</xsl:text>
  </xsl:for-each>
  <xsl:text>) )</xsl:text>
</xsl:template>

<xsl:template mode="makeWhereClause" match="report/@patientId">
  <xsl:text> AND PATIENT_ID = </xsl:text>
  <xsl:value-of select="."/>
</xsl:template>

<xsl:template mode="makeWhereClause" match="report/@orderId">
  <xsl:text> AND MEDICAL_ORDER_ID = </xsl:text>
  <xsl:value-of select="."/>
</xsl:template>

<xsl:template mode="makeWhereClause" match="report/@institutionId">
  <xsl:text> AND INSTITUTION_ID = </xsl:text>
  <xsl:value-of select="."/>
</xsl:template>

<xsl:template mode="makeWhereClause" match="/|@*|node()">
  <xsl:apply-templates mode="makeWhereClause" select="@*|node()"/>
</xsl:template>

</xsl:transform>
