xquery version "3.0";
(:
    ART-DECOR® STANDARD COPYRIGHT AND LICENSE NOTE
    Copyright © ART-DECOR Expert Group and ART-DECOR Open Tools GmbH
    see https://docs.art-decor.org/copyright and https://docs.art-decor.org/licenses

    This file is part of the ART-DECOR® tools suite.
:)

import module namespace vs  = "http://art-decor.org/ns/decor/valueset" at "../api/api-decor-valueset.xqm";

let $references         := if (request:exists()) then request:get-data()/* else ()
(:let $references         := 
        <associations>
            <association conceptId="..." effectiveDate="..." valueSet="2.16.840.1.113883.3.1937.99.62.3.11.7" flexibility="2014-12-10T00:00:00"/>
        </associations>:)
let $projectPrefix      := if (request:exists()) then request:get-parameter('project',())[string-length()>0][1] else ('demo1-')
let $projectVersion   := if (request:exists()) then request:get-parameter('version',())[string-length()>0][1] else ()
let $projectLanguage  := if (request:exists()) then request:get-parameter('language',())[string-length()>0][1] else ()
let $serialize        := if (request:exists()) then not(request:get-parameter('serialize', 'true')[string-length()>0][1] = 'false') else true()

return
<valueSets>
{
    for $reference in $references/*[string-length(@valueSet)>0]
    let $ref        := $reference/@valueSet
    let $eff        := if ($reference/@flexibility[string-length()>0]) then $reference/@flexibility else ('dynamic')
    let $valueSets  := vs:getExpandedValueSetByRef($ref, $eff, $projectPrefix, $projectVersion, $projectLanguage, $serialize)
    return
        for $valueSet in $valueSets/descendant-or-self::valueSet
        order by xs:dateTime($valueSet/@effectiveDate) descending
        return
            <valueSet>
            {
                $valueSet/(@* except @conceptId),
                attribute conceptId {$reference/@conceptId},
                if (not($valueSet/@url)) then $valueSet/parent::*/@url else (),
                if (not($valueSet/@ident)) then $valueSet/parent::*/@ident else (),
                $valueSet/node()
            }
            </valueSet>
}
</valueSets>