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 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 ('demo1-')
let $templateId             := if (request:exists()) then request:get-parameter('id',()) else ('2.16.840.1.113883.3.1937.99.62.3.10.4')
let $templateEffectiveDate  := if (request:exists()) then request:get-parameter('effectiveDate',()) else ('2009-10-01T00:00:00')


let $decor                  := $get:colDecorData//decor[project/@prefix=$project]
let $projectvaluesets       := $decor/terminology/valueSet[@id]
let $projecttemplates       := $decor/rules/template[@id]
let $starttemplate          := $projecttemplates[@id=$templateId]
let $starttemplate          := if ($templateEffectiveDate castable as xs:dateTime) 
                               then $starttemplate[@effectiveDate=$templateEffectiveDate] 
                               else $starttemplate[@effectiveDate=max($starttemplate/xs:dateTime(@effectiveDate))]

let $templateChain          := templ:getTemplateList($templateId,(),$templateEffectiveDate,$project,(),true(),$templ:TREETYPELIMITEDMARKED)

let $valueSetChain          :=
    for $t in $templateChain//class/template/template
    return
    (
        for $ref in $projecttemplates[@id=$t/@id][@effectiveDate=$t/@effectiveDate]//vocabulary[@valueSet]
        let $reff       := $ref/@valueSet
        let $eff        := $ref/@flexibility[not(.='dynamic')]
        let $ishere     := 
            if ($ref/@flexibility[not(.='dynamic')])
            then $projectvaluesets[@id=$ref/@valueSet][@effectiveDate=$ref/@flexibility[not(.='dynamic')]]
            else $projectvaluesets[@id=$ref/@valueSet]
        group by $reff, $eff
        return
            if (empty($ishere))
            then <valueSet uuid="{util:uuid()}" ref="{$reff[1]}" flexibility="{if ($eff) then $eff[1] else 'dynamic'}"/>
            else <valueSet uuid="{util:uuid()}" id="{$reff[1]}" flexibility="{if ($eff) then $eff[1] else 'dynamic'}" 
                   name="{$ishere[1]/@name}" displayName="{$ishere[1]/@displayName}" statusCode="{$ishere[1]/@statusCode}" />
    )
    
return
    <result valueSets="{count($valueSetChain)}" templates="{count($templateChain//class/template/template)}">
    {
        <terminology>
        {
            $valueSetChain
        }
        </terminology>
    }
    {
        $templateChain
    }
    </result>
    