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

import module namespace get    = "http://art-decor.org/ns/art-decor-settings" at "../modules/art-decor-settings.xqm";
import module namespace aduser = "http://art-decor.org/ns/art-decor-users" at "../api/api-user-settings.xqm";

let $newUserEmail      := if (request:exists()) then request:get-parameter('email','') else ('')
let $updateAllProjects := if (request:exists()) then request:get-parameter('updateprojects','false') else ('false')
let $updateProject     := if (request:exists()) then request:get-parameter('updateproject',()) else ()

let $userUpdate        := 
    if (string-length($updateProject)=0) then
        aduser:setUserEmail(get:strCurrentUserName(),$newUserEmail)
    else ()
let $userUpdate        := 
    if ($updateAllProjects='true') then
        for $author in $get:colDecorData//decor/project/author[@username=get:strCurrentUserName()]
        return
            if ($author[@email]) then 
                update value $author/@email with $newUserEmail
            else (
                update insert attribute email {$newUserEmail} into $author
            )
    else if (string-length($updateProject)>0) then
        for $author in $get:colDecorData//decor/project[@prefix=$updateProject]/author[@username=get:strCurrentUserName()]
        return
            if ($author[@email]) then 
                update value $author/@email with $newUserEmail
            else (
                update insert attribute email {$newUserEmail} into $author
            )
    else ()

return
    <email username="{get:strCurrentUserName()}" default="{aduser:getUserEmail(get:strCurrentUserName())}">
    {
        for $author in $get:colDecorData//decor/project/author[@username=get:strCurrentUserName()]
        return
            <project prefix="{$author/parent::project/@prefix/string()}" name="{$author/parent::project/name[1]/text()}" email="{$author/@email/string()}"/>
    }
    </email>