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 get = "http://art-decor.org/ns/art-decor-settings" at "art-decor-settings.xqm";
import module namespace vs  = "http://art-decor.org/ns/decor/valueset" at "../api/api-decor-valueset.xqm";
import module namespace art = "http://art-decor.org/ns/art" at "art-decor.xqm";
declare namespace xs        = "http://www.w3.org/2001/XMLSchema";
declare namespace xforms    = "http://www.w3.org/2002/xforms";

let $id                 := if (request:exists()) then request:get-parameter('id',())[string-length()>0][1] else ()
let $name               := if (request:exists()) then request:get-parameter('name',())[string-length()>0][1] else ()
let $ref                := if (request:exists()) then request:get-parameter('ref',())[string-length()>0][1] else ()
let $useRegexMatching   := if (request:exists()) then request:get-parameter('regex',false())[string-length()>0][1] else (false())

let $effectiveDate      := if (request:exists()) then request:get-parameter('effectiveDate',())[string-length()>0][1] else ()
let $projectPrefix      := if (request:exists()) then request:get-parameter('project',())[string-length()>0][1] else ('demo1-')

let $decor              :=
    if (empty($projectPrefix)) then
        $get:colDecorData//decor/terminology/codeSystem[(@id|@ref)=$id]
    else (
        $get:colDecorData//decor[project/@prefix=$projectPrefix]
    )

let $codeSystems        := 
    if (not(empty($id))) then
        $decor/terminology/codeSystem[(@id|@ref)=$id]
    
    else if (not(empty($name))) then
        $decor/terminology/codeSystem[@name=$name]
    
    else if (not(empty($ref)) and not(empty($projectPrefix))) then
        $decor/terminology/codeSystem[(@id|@ref|@name)=$ref]
    
    else ()

return
<codeSystemVersions>
{
    for $codeSystem in $codeSystems
    order by xs:dateTime($codeSystem/@effectiveDate) descending
    return
        <codeSystem>
        {
            $codeSystem/@*,
            if (not($codeSystem/@url)) then $codeSystem/parent::*/@url else (),
            if (not($codeSystem/@ident)) then (attribute ident {$projectPrefix}) else (),
            for $node in $codeSystem/desc
            return
                art:serializeNode($node)
            ,
            $codeSystem/conceptList
        }
        </codeSystem>
}
</codeSystemVersions>