xquery version "1.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 templ   = "http://art-decor.org/ns/decor/template" at "../api/api-decor-template.xqm";

let $project                := if (request:exists()) then request:get-parameter('project','') else ('mp-')
let $ref                    := if (request:exists()) then request:get-parameter('ref',())[string-length()>0] else ()
let $effectiveDate          := if (request:exists()) then request:get-parameter('effectiveDate',())[string-length()>0] else ()

let $templateAssociations   := art:getTemplateAssociations($project, (), (), $ref, $effectiveDate)

return
<templateAssociations>
{
    for $association in $templateAssociations
    (: note: may not have a match in case of template/@ref :)
    let $template   := $association/../template[@id=$association/@templateId][@effectiveDate=$association/@effectiveDate]
    let $template   := 
        if ($template) then $template[1] else (templ:getTemplateById($association/@templateId, $association/@effectiveDate, $project)//template[@effectiveDate])[1]
    return
        if ( $template ) then (
            element {$association/name()} {
                $association/@*,
                for $concept in $association/concept
                (: note when duplicate elementIds in a template exist we could get multiple hits... :)
                let $particles      := $template//element[@id = $concept/@elementId] | $template//attribute[@id = $concept/@elementId]
                
                return
                    <concept>
                    {
                        $concept/(@* except @elementName), 
                        if ($particles) then (
                            attribute elementName {
                                for $particle in $particles
                                let $initialName    := concat(if ($particle[self::attribute/@name]) then '@' else (),$particle/@name)
                                return 
                                    if ($particle/attribute[@name='LongName'][@value]) then 
                                        (:HL7v2 convenience ... :)
                                        concat($initialName,' (',$particle/attribute[@name='LongName'][1]/@value,')')
                                    else 
                                        $initialName
                            }
                        ) else ()
                    }
                    </concept>
            }
        ) else (
            $association
        )
}
</templateAssociations>