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

(: get dataset from request :)
let $codeSystems        := if (request:exists()) then (request:get-data()/codeSystems) else ()
let $decor              := if (empty($codeSystems/@projectPrefix)) then () else art:getDecorByPrefix($codeSystems/@projectPrefix)
let $projectPrefix      := $decor/project/@prefix
let $canEdit            := if (empty($projectPrefix)) then (false()) else decor:authorCanEditP($decor, $decor:SECTION-TERMINOLOGY)

let $store              :=
    if ($canEdit) then
        for $codeSystem in $codeSystems/codeSystem
        let $storedCodeSystem := $decor/terminology/codeSystem[@ref=$codeSystem/@ref]
        return
            if ($storedCodeSystem) then
                if ($codeSystem[@action = 'delete']) then
                    update delete $storedCodeSystem
                else
                    update replace $storedCodeSystem with $codeSystem
            else if (not($storedCodeSystem) and $decor/terminology/valueSet) then
                update insert $codeSystem preceding $decor/terminology/valueSet[1]
            else (
                update insert $codeSystem into $decor/terminology
            )
    else ()

return
<data-safe>{$canEdit}</data-safe>
