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 template ref into rules
   Input: post of ref element:
   <template projectPrefix="demo1-" ref="x-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";

(: <structuredefinition referencedFrom="" canonicalUri="" publicationUrl="" id="" displayName="" projectPrefix=""/> :)
let $objref         := if (request:exists()) then request:get-data()/structuredefinition else ()
let $projectPrefix  := $objref/@projectPrefix

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

(: get user for permission check:)
let $user           := get:strCurrentUserName()

let $alreadyrefed   := $decor/rules/structuredefinition[@canonicalUri = $objref/@canonicalUri]
let $ref            :=
    <structuredefinition referencedFrom="{$objref/@referencedFrom}" canonicalUri="{$objref/@canonicalUri}" publicationUrl="{$objref/@publicationUrl}" id="{util:uuid()}" strucdefId="{$objref/@id}" displayName="{$objref/@displayName}"/>
    
return
    if ($decor) then (
        if (decor:authorCanEditP($decor, $user, $decor:SECTION-RULES)) then (
            if ($ref) then (
                if ($alreadyrefed) then (
                    (: this allows us to change the displayName while not breaking the reference :)
                    let $u1 :=
                        update replace $alreadyrefed/@displayName with $ref/@displayName
                        
                    return
                        <response>{$ref/@*,'OK'}</response>
                )
                else (
                    let $u1 :=
                        if ($decor/rules) then () else (
                            update insert <rules/> following ($decor/ids | $decor/terminology)[last()]
                        )
                    let $u2 := update insert $ref into $decor/rules
                    
                    return
                        <response>{$ref/@*,'OK'}</response>
                )
            )
            else (
                <response>MISSING @ref and/or @name</response>
            )
        )
        else (
            <response>NO PERMISSION</response>
        )
    )
    else (
        <response>PROJECT {$projectPrefix} NOT FOUND</response>
    )