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 vs  = "http://art-decor.org/ns/decor/valueset" at "../api/api-decor-valueset.xqm";

declare namespace request = "http://exist-db.org/xquery/request";
declare namespace response = "http://exist-db.org/xquery/response";
declare namespace xdb = "http://exist-db.org/xquery/xmldb";
declare namespace hl7 = "urn:hl7-org:v3";
declare option exist:serialize "indent=yes";
declare option exist:serialize "omit-xml-declaration=no";

let $projectPrefix              := if (request:exists()) then request:get-parameter('prefix',())[string-length() > 0] else 'rivmsp-'

let $check                      :=
    if (empty($projectPrefix)) then (
        if (request:exists()) then (response:set-status-code(404), response:set-header('Content-Type','text/xml; charset=utf-8'), <error>Missing parameter 'prefix'</error>) else ()
    ) else
    if (count($projectPrefix) gt 1) then (
        if (request:exists()) then (response:set-status-code(500), response:set-header('Content-Type','text/xml; charset=utf-8'), <error>Multiple occurences of parameter 'prefix' not supported</error>) else ()
    ) else ()

(:let $projectPrefix := 'peri20-':)
let $decor                      := if (empty($projectPrefix)) then () else art:getDecorByPrefix($projectPrefix)
let $valueSets                  := art:currentValuesets($decor)
let $allTerminologyAssociations := $decor/terminology/terminologyAssociation

return (
    if (request:exists()) then response:set-header('Content-Type','text/xml; charset=utf-8') else (),
    <terminologyAssociations prefix="{$projectPrefix}">
    {
        for $valueSetAssociation in $decor//terminologyAssociation[@valueSet]
        for $valueSet in vs:getValueSetById($valueSetAssociation/@valueSet, $valueSetAssociation/@flexibility, $projectPrefix, false())//valueSet[@id]
        for $conceptList in $decor//dataset//conceptList[@id = $valueSetAssociation/@conceptId][not(ancestor::history)]
        for $codedConcept in $conceptList/concept
        for $codeAssociation in $allTerminologyAssociations[@conceptId = $codedConcept/@id]
        for $code in $valueSet/conceptList/concept[@code = $codeAssociation/@code][@codeSystem = $codeAssociation/@codeSystem]
        return
            if ($codedConcept/name = $code/@displayName) then () else (
                <terminologyAssociation conceptId="{$codedConcept/@id}" name="{$codedConcept/name}" displayName="{$code/@displayName}" valueSet="{$valueSet/@name}"/>
            )
    }
    </terminologyAssociations>
)