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";
declare namespace request       = "http://exist-db.org/xquery/request";

let $labels             := if (request:exists()) then (request:get-data()/labels) else ()
let $projectPrefix      := if (request:exists()) then (request:get-parameter('project',())) else ()

(:
    <labels>
        <label code="" name="" color="">
            <desc language="en-US">....</desc>
        </label>
    </labels>
:)
let $decor              := $get:colDecorData//decor[project/@prefix=$projectPrefix]
let $currentIssues      := $decor/issues
let $currentLabels      := $currentIssues/labels
let $username           := get:strCurrentUserName()
let $isauthor           := $decor/project/author[@username=$username]

let $newLabels          :=
    <labels>
    {
        for $label in $labels/label[string-length(@code)>0][string-length(@name)>0]
        return
            <label>
            {
                $label/(@code|@name|@color)
                ,
                for $node in $label/desc[string-length(string-join(.//text(),''))>0]
                return
                    art:parseNode($node)
            }
            </label>
    }
    </labels>
    
let $update             :=
    if ($labels and $isauthor) then
        let $update     :=
            if (not($currentIssues)) then
                update insert <issues>{$newLabels}</issues> into $decor
            else if (not($currentLabels)) then
                update insert $newLabels preceding $currentIssues/*[1]
            else (
                update replace $currentLabels with $newLabels
            )
        return 
            true()
    else (
        false()
    )

return
    <data-safe>true</data-safe>
