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.
:)

(:
   Xquery for inserting codeSystem ref into terminology
   Input: post of ref element:
   <codeSystem projectPrefix="demo1-" ref="ref-oid" name="x" displayName="y"/>
:)
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 decor           = "http://art-decor.org/ns/decor" at "../api/api-decor.xqm";

let $objref         := if (request:exists()) then request:get-data()/codeSystem else ()
let $projectPrefix  := $objref/@projectPrefix

(:get decor file:)
let $decor          := art:getDecorByPrefix($projectPrefix)

(: get user for permission check:)
let $user           := get:strCurrentUserName()
let $ref            :=
    if ($objref[@ref[string-length() > 0]][@name[string-length() > 0]]) then 
        element {$objref/name()} {
            $objref/@ref, 
            $objref/@name, 
            if ($objref/@displayName[string-length() > 0]) then 
                $objref/@displayName
            else (
                attribute displayName {$objref/@name}
            )
        }
    else ()
    
let $alreadyrefed   := $decor/terminology/codeSystem[@ref = $objref/@ref]

return
    if ($decor) then (
        if (decor:authorCanEditP($decor, $user, $decor:SECTION-TERMINOLOGY)) then (
            if ($ref) then (
                if ($alreadyrefed) then (
                    <response>OK</response>
                )
                else (
                    let $u1 :=
                        if ($decor/terminology) then () else (
                            update insert <terminology/> following $decor/ids
                        )
                    let $u2 := update insert $ref into $decor/terminology
                    
                    return
                    <response>OK</response>
                )
            )
            else (
                <response>MISSING @ref and/or @name</response>
            )
        )
        else (
            <response>NO PERMISSION</response>
        )
    )
    else (
        <response>PROJECT {$projectPrefix} NOT FOUND</response>
    )