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 %private function local:preparePrototype($prototype as element()) as element() {
    <prototype>
    {
        $prototype/@ref[not(. = '')]
        ,
        for $data in $prototype/data
        return
            <data>
            {
                $data/@*,
                for $desc in $data/desc
                return
                    art:parseNode($desc)
            }
            </data>
    }
    </prototype>
};

(: get community from request :)
let $newCommunity := request:get-data()/community

(: get project parent collection  :)
let $parentCollection := util:collection-name($get:colDecorData//decor[project/@id = $newCommunity/@projectId])

let $community :=
    <community>
    {
        $newCommunity/@name,
        $newCommunity/@projectId,
        if (string-length($newCommunity/@displayName) = 0) then
            attribute displayName {$newCommunity/@name}
        else
            ($newCommunity/@displayName),
        for $desc in $newCommunity/desc
        return
            art:parseNode($desc)
        ,
        $newCommunity/access
        ,
        local:preparePrototype($newCommunity/prototype)
    }
    </community>


return
    <result>
        {xmldb:store($parentCollection, concat('community-', $newCommunity/@name, '.xml'), $community)}
    </result>