xquery version "1.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 get = "http://art-decor.org/ns/art-decor-settings" at "art-decor-settings.xqm";
import module namespace art = "http://art-decor.org/ns/art" at "art-decor.xqm";
import module namespace cs  = "http://art-decor.org/ns/decor/codesystem" at "../api/api-decor-codesystem.xqm";
import module namespace vs  = "http://art-decor.org/ns/decor/valueset" at "../api/api-decor-valueset.xqm";

let $projectPrefix          := if (request:exists()) then request:get-parameter('project',()) else ()
let $id                     := if (request:exists()) then request:get-parameter('id',())[string-length() gt 0][1] else ()
let $effectiveDate          := if (request:exists()) then request:get-parameter('effectiveDate',())[. castable as xs:dateTime][1] else ()

let $codeSystemsAll         :=
    if (empty($id)) then () else (
        if (empty($projectPrefix)) then
            cs:getCodeSystemById($id, ())
        else (
            cs:getCodeSystemById($id, (), $projectPrefix, ())
        )
    )

let $id                     := if (empty($id)) then $codeSystemsAll/descendant-or-self::codeSystem/(@id | @ref) else $id
let $mostRecent             := string(max($codeSystemsAll/descendant-or-self::codeSystem/xs:dateTime(@effectiveDate)))
let $effectiveDate          := if ($effectiveDate castable as xs:dateTime) then $effectiveDate else $mostRecent
let $name                   := $codeSystemsAll/descendant-or-self::codeSystem[@id]/@name

let $decor                  := $get:colDecorData/decor

let $valueSetsAll           := $decor/terminology/valueSet[.//@codeSystem = $id]
let $allTemplAssociations   := $decor/rules/template[.//vocabulary[@codeSystem = $id]]

return
<usage prefix="{$projectPrefix}" id="{$id}" name="{$name}" effectiveDate="{$effectiveDate}" mostRecent="{$mostRecent}" isMostRecent="{$mostRecent = $effectiveDate}">
{
    for $item in $valueSetsAll
    return
        element {name($item)} {
            $item/@id, $item/@name, attribute displayName {($item/@displayName, $item/@name)[1]}, $item/@effectiveDate, 
            attribute prefix {$item/ancestor::decor/project/@prefix}, attribute projectName {$item/ancestor::decor/project/name[1]}
        }
}
{
    for $item in $allTemplAssociations
    return
        element {name($item)} {
            $item/@id, $item/@name, attribute displayName {($item/@displayName, $item/@name)[1]}, $item/@effectiveDate, 
            attribute prefix {$item/ancestor::decor/project/@prefix}, attribute projectName {$item/ancestor::decor/project/name[1]}
        }
}
</usage>

