<!--
     zipWsrrGraphQueryResponse
-->
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:func="http://exslt.org/functions"
  xmlns:dp="http://www.datapower.com/extensions"
  extension-element-prefixes="dp"
  exclude-result-prefixes="func"
>
  <!-- we need to output a .zip file, do binaryNode output -->
  <dp:output-mapping href="store:///pkcs7-convert-input.ffd" type="ffd"/>


  <!-- nice to have functions for dealing with attachments -->
  <func:function name="func:cid">
    <xsl:param name="name"/>  <func:result select="concat('cid:',$name)"/>
  </func:function>

  <func:function name="func:att">
    <xsl:param name="name"/>

    <func:result select="concat('attachment://swa/',func:cid($name))"/>
  </func:function>

  <func:function name="func:zip">
    <xsl:param name="name"/> <xsl:param name="fname"/>

    <func:result 
       select="concat(func:att($name),'?Archive=zip&amp;Filename=',$fname)"/>
  </func:function>


  <!-- name of auxiliary Content-ID (CID) used -->
  <xsl:variable name="aux" select="'aux'"/>


  <!-- base64 encoded .zip just containing (empty) "dummy" directory -->
  <xsl:variable name="emptyZip" 
    select="concat(
'UEsDBAoAAAAAAE0ga0IAAAAAAAAAAAAAAAAGABwAZHVtbXkvVVQJAANBST1RQUk9UXV4CwABBPQB',
'AAAE9QEAAFBLAQIeAwoAAAAAAE0ga0IAAAAAAAAAAAAAAAAGABgAAAAAAAAAEAD9QQAAAABkdW1t',
'eS9VVAUAA0FJPVF1eAsAAQT0AQAABPUBAABQSwUGAAAAAAEAAQBMAAAAQAAAAAAA'
            )"
  />


  <xsl:template match="/">
    <!-- crate "swa" context, content not used, so empty string good enough -->
    <dp:set-variable name=" 'var://context/swa' " value=" '' "/>

    <!-- create "empty" archive attachment for collecting files ($aux CID) -->
    <dp:url-open 
      target="{func:att($aux)}" 
      data-type="base64" 
      response="ignore"
      content-type="application/zip"
    >
      <xsl:value-of select="$emptyZip" />
    </dp:url-open>

    <!-- just copy over each file existing in WSRR GraphQuery response ... -->
    <xsl:for-each 
      select="/*/*/*/*/*[local-name()='WSRR']/*[local-name()='artefacts']"
    >
      <!-- into the .zip archive attachment -->
      <dp:url-open 
        target="{func:zip($aux,@name)}" 
        data-type="base64" 
        response="ignore"
        resolve-mode="swa"
      >
        <xsl:value-of select="@content" />
      </dp:url-open>
    </xsl:for-each> 

    <!-- extract newly created (and populated!) .zip archive -->
    <xsl:variable name="newzip">    
      <dp:url-open
        target="{func:zip($aux,@name)}"
        response="binaryNode"
      />
    </xsl:variable>

    <!-- frame as required by dp:output-mapping -->
    <object>
      <message>
        <!-- return the generated .ip archive -->
        <xsl:copy-of select="$newzip/result/binary/node()"/>
      </message>
    </object>
  </xsl:template>

</xsl:stylesheet>