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

(: are we just testing what would happen (false), 
   or actually doing it too (true) :)
declare variable $testMode   := if (request:exists()) then request:get-parameter('test','false') else ('true');
(: do we replace all associations tied into the original concept / conceptList / conceptList/concept ('replace'), 
   or do we only add what we don't already have ('add') :)
declare variable $runMode    := if (request:exists()) then request:get-parameter('mode','add') else ('add');

let $deid                   := if (request:exists()) then request:get-parameter('id',())[string-length()>0]                         else ('2.16.840.1.113883.3.1937.99.62.3.2.5')
let $deed                   := if (request:exists()) then request:get-parameter('effectiveDate',())[string-length()>0]              else ()
let $trid                   := if (request:exists()) then request:get-parameter('transactionId',())[string-length()>0]              else ('2.16.840.1.113883.3.1937.99.62.3.4.2')
let $tred                   := if (request:exists()) then request:get-parameter('transactionEffectiveDate',())[string-length()>0]   else ('2012-09-05T16:59:35')

let $trid := ()
let $tred := ()

let $concept            := 
    if (string-length($deid)=0)     then () 
    else
    if (string-length($trid)=0) then art:getConcept($deid, $deed) 
    else (
        art:getTransactionConcept($deid, $deed, $trid, $tred)
    )

return
    <result testing-mode="{$testMode}" run-mode="{$runMode}" concept="{$deid}" transaction="{$trid}">
    {
        if (empty($concept)) then () else (
            let $originalConcept        := 
                if (string-length($trid) gt 0) then ($concept) else if ($concept[inherit | contains]) then (art:getOriginalForConcept($concept)) else ()
            
            return
                if ($originalConcept) then (
                    art:addAssociations(art:getConceptAssociations($originalConcept), $concept, $runMode='replace', $testMode='true')/*
                ) else ()
        )
    }
    </result>
