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";
declare namespace xs="http://www.w3.org/2001/XMLSchema";
declare namespace xforms="http://www.w3.org/2002/xforms";

let $missingCodeSystems := request:get-data()/missingCodeSystems
(:let $missingCodeSystems :=
<missingCodeSystems projectPrefix="sandbox-">
<codeSystem ref="2.16.840.1.113883.5.1008" name="null" displayName="null"/>
</missingCodeSystems>:)

let $decor              := $get:colDecorData//decor[project/@prefix=$missingCodeSystems/@projectPrefix]

let $insert             :=
    for $codeSystem in $missingCodeSystems/codeSystem
    return
        if ($decor/terminology/valueSet) then
            update insert $codeSystem preceding  $decor/terminology/valueSet[1]
        else (
            update insert $codeSystem into  $decor/terminology
        )

return
<missingCodeSystems projectPrefix="{$decor/project/@prefix}"/>
