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

let $templateAssociation    := if (request:exists()) then request:get-data()/templateAssociation else (
    <templateAssociation projectPrefix="demo1-" templateId="2.16.840.1.113883.3.1937.99.62.3.10.1" effectiveDate="2013-09-24T18:20:25">
        <concept ref="2.16.840.1.113883.3.1937.99.62.3.2.1" effectiveDate="2012-05-30T11:32:36" elementId="2.16.840.1.113883.3.1937.99.62.3.9.1"/>
    </templateAssociation>
)
let $decor                  := $get:colDecorData//decor[project/@prefix=$templateAssociation/@projectPrefix]
let $user                   := get:strCurrentUserName()
let $template               := $decor//template[@id=$templateAssociation/@templateId][@effectiveDate=$templateAssociation/@effectiveDate]|$decor//template[@ref=$templateAssociation/@templateId]
let $newAssociationInsert   :=
    <insert>
    {
        comment{$template/@displayName}
    }
    <templateAssociation>
    {
        $templateAssociation/(@templateId|@effectiveDate),
        for $c in $templateAssociation/concept
        let $originalConcept    := art:getOriginalForConcept(art:getConcept($c/@ref, $c/@effectiveDate))
        return (
            comment {' Concept', $originalConcept/@type, ':', replace(data($originalConcept/name[1]), '--', '-\\-'), ' '},
            <concept>
            {
                $c/@ref[not(. = '')], 
                $c/@effectiveDate[not(. = '')], 
                $c/@elementId[not(. = '')], 
                $c/@elementPath[not(. = '')]
            }
            </concept>
        )
    }
    </templateAssociation>
    </insert>

(: check for existing association for template, add concept :)
let $association            := $decor//templateAssociation[@templateId=$templateAssociation/@templateId][@effectiveDate=$templateAssociation/@effectiveDate]

return
    if ($user=$decor/project/author/@username) then
        if ($association) then (
            update insert $newAssociationInsert/templateAssociation/node() into $association,
            <response>OK</response>
        )
        else (
            update insert $newAssociationInsert/node() preceding $template,
            <response>OK</response>
        )
    else (
        <response>NO PERMISSION</response>
    )