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 $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')
(: Modes: all, diff, normal (default)
    - all: retrieve any dataset and transaction terminologyAssociations and identifierAssociations for this concept
    - diff: as 'all', but trimmed only to those 
        - in any transactions if this a dataset concept ($trid is empty)
        - at dataset level if this a transaction concept ($trid is not empty)
    - normal (default): retrieve any terminologyAssociations and identifierAssociations for this concept at the appropriate level
        - in transaction ($trid is not empty)
        - at dataset level ($trid is empty)
:)
let $mode               := if (request:exists()) then request:get-parameter('mode',())[string-length()>0]                       else ('diff')

let $concept            :=
    if (empty($deid)) then () else if (empty($tred)) then art:getConcept($deid, $deed) else art:getTransactionConcept($deid, $deed, $trid, $tred)

return
    if ($concept[ancestor::dataset]) then 
        art:getConceptAssociations($concept, art:getOriginalForConcept($concept), $mode, true()) 
    else
    if ($concept) then 
        art:getConceptAssociations($concept, art:getOriginalForConcept(art:getConcept($concept/@ref, $concept/@flexibility)), $mode, true()) 
    else
    (<associations/>)
(:<X conceptId="{$deid}" transactionId="{$trid}">
    <all>{art:getConceptAssociations($concept, 'all', true())}</all>
    <diff>{art:getConceptAssociations($concept, 'diff', true())}</diff>
    <normal>{art:getConceptAssociations($concept, '', true())}</normal>
</X>:)
