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 setting template id
   Input: post of id-management instance
   <id-management old="" new="" effectiveDate=""/>
:)
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";

let $idm        := request:get-data()/id-management
let $template   := $get:colDecorData//template[@id=$idm/old][@effectiveDate=$idm/effectiveDate]
let $lock       := decor:getLocks($template/lock/@ref, $template/lock/@effectiveDate, (), false())

(:get decor file for permission check:)
let $decor      := $get:colDecorData//template[@id=$idm/old][@effectiveDate=$idm/effectiveDate]/ancestor::decor

let $idUpdate :=
    if (decor:authorCanEditP($decor, $decor:SECTION-RULES)) then (
        if ($lock) then
            <response>{$lock/node()}</response>
        else (
            let $storedTemplateAssociation  := $get:colDecorData//templateAssociation[@templateId=$idm/old][@effectiveDate=$idm/effectiveDate]
            let $storedTemplate             := $get:colDecorData//template[@id=$idm/old][@effectiveDate=$idm/effectiveDate]
            let $update                     := update value $storedTemplateAssociation/@templateId with $idm/new/text()
            let $update                     := update value $storedTemplate/@id with $idm/new/text()
            
            return <response>OK</response>
        )
    )
    else (
        <response>NO PERMISSION</response>
    )

return
    $idUpdate