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";
declare namespace request = "http://exist-db.org/xquery/request";
declare namespace response = "http://exist-db.org/xquery/response";
declare namespace hl7="urn:hl7-org:v3";

declare %private function local:getTemplateDisplayName($ref as xs:string?,$flexibility as xs:string?) as xs:string? {
    if (string-length($ref)>0) then
        let $templates           := collection($get:strDecorData)//template[@id=$ref]|collection($get:strDecorData)//template[@name=$ref]
        let $searchEffectiveDate :=
            if (matches($flexibility,'^\d{4}')) then (
                $flexibility
            ) else (
                string(max($templates/xs:dateTime(@effectiveDate)))
            )
        let $displayName         := ($templates[@effectiveDate=$searchEffectiveDate]/@displayName)[1]
        return
            if (string-length($displayName)>0) then ($displayName) else (($templates[@effectiveDate=$searchEffectiveDate]/@name)[1])
   else ()
};

declare %private function local:filterDataset($concept as element(),$representingTemplate as element()) as element()* {
    let $id := $concept/@id
    
    return
        if (exists($representingTemplate/concept[@ref=$id])) then
            $concept
        else (),
        for $subConcept in $concept/concept
        return
            local:filterDataset($subConcept,$representingTemplate)

};
declare %private function local:scenarioBasics($transaction as element(), $defaultLanguage as xs:string) as element() {
    let $type := $transaction/@type
    return
        if ($type='group') then
            <transaction id="{$transaction/@id}" type="{$transaction/@type}" label="{$transaction/@label}" model="{$transaction/@model}" effectiveDate="{$transaction/@effectiveDate}" statusCode="{$transaction/@statusCode}" expirationDate="{$transaction/@expirationDate}" versionLabel="{$transaction/@versionLabel}" canonicalUri="{$transaction/@canonicalUri}">
            {
                $transaction/@lastModifiedDate,
                for $name in $transaction/name
                return
                    art:serializeNode($name)
                ,
                for $desc in $transaction/desc
                return
                    art:serializeNode($desc)
                ,
                for $trigger in $transaction/trigger
                return
                    art:serializeNode($trigger)
                ,
                for $condition in $transaction/condition
                return
                    art:serializeNode($condition)
                ,
                for $dependencies in $transaction/dependencies
                return
                    art:serializeNode($dependencies)
                ,
                (: new ... 2021-05-21 :)
                for $node in $transaction/publishingAuthority
                return
                    <publishingAuthority>
                    {
                        $node/@id[not(. = '')],
                        $node/@name[not(. = '')],
                        for $addr in $node/addrLine
                        return
                            art:serializeNode($addr)
                    }
                    </publishingAuthority>
                ,
                (:new since 2021-05-21 :)
                if ($transaction/property) then
                    for $node in $transaction/property
                    return
                        art:serializeNode($node)
                else (
                    <property name="" datatype="text"/>
                )
                ,
                (: new ... 2021-05-21 :)
                for $node in $transaction/copyright
                return
                    art:serializeNode($node)
                ,
                for $t in $transaction/transaction
                return
                    local:scenarioBasics($t, $defaultLanguage)
            }
            </transaction>
        else (
            <transaction id="{$transaction/@id}" type="{$transaction/@type}" label="{$transaction/@label}" model="{$transaction/@model}" effectiveDate="{$transaction/@effectiveDate}" statusCode="{$transaction/@statusCode}" expirationDate="{$transaction/@expirationDate}" versionLabel="{$transaction/@versionLabel}" canonicalUri="{$transaction/@canonicalUri}">
            {
                for $name in $transaction/name
                return
                    art:serializeNode($name)
                ,
                for $desc in $transaction/desc
                return
                    art:serializeNode($desc)
                ,
                for $trigger in $transaction/trigger
                return
                    art:serializeNode($trigger)
                ,
                for $condition in $transaction/condition
                return
                    art:serializeNode($condition)
                ,
                for $dependencies in $transaction/dependencies
                return
                    art:serializeNode($dependencies)
                ,
                (: new ... 2021-05-21 :)
                for $node in $transaction/publishingAuthority
                return
                    <publishingAuthority>
                    {
                        $node/@id[not(. = '')],
                        $node/@name[not(. = '')],
                        for $addr in $node/addrLine
                        return
                            art:serializeNode($addr)
                    }
                    </publishingAuthority>
                ,
                (:new since 2021-05-21 :)
                if ($transaction/property) then
                    for $node in $transaction/property
                    return
                        art:serializeNode($node)
                else (
                    <property name="" datatype="text"/>
                )
                ,
                (: new ... 2021-05-21 :)
                for $node in $transaction/copyright
                return
                    art:serializeNode($node)
            }
            <actors>
            {
                for $actor in $transaction/actors/actor
                return
                    <actor id="{$actor/@id}" role="{$actor/@role}">
                        {$get:colDecorData//scenarios/actors/actor[@id=$actor/@id]/name}
                    </actor>
            }
            </actors>
            <representingTemplate ref="{$transaction/representingTemplate/@ref}" flexibility="{$transaction/representingTemplate/@flexibility}" templateDisplayName="{local:getTemplateDisplayName($transaction/representingTemplate/@ref,$transaction/representingTemplate/@flexibility)}" 
                                  sourceDataset="{$transaction/representingTemplate/@sourceDataset}" sourceDatasetFlexibility="{$transaction/representingTemplate/@sourceDatasetFlexibility}"
                                  representingQuestionnaire="{$transaction/representingTemplate/@representingQuestionnaire}" representingQuestionnaireFlexibility="{$transaction/representingTemplate/@representingQuestionnaireFlexibility}"
            >
            {
                for $concept in $transaction/representingTemplate/concept
                return
                    <concept>
                    {
                        $concept/@*,
                        $concept/obligation,
                        for $node in $concept/context
                        return
                            art:serializeNode($node)
                        ,
                        for $condition in $concept/condition
                        return
                            <condition>
                            {
                                $condition/@*,
                                $condition/desc,
                                if ($condition[desc]) then () else if (string-length(.)=0) then () else (
                                    <desc language="{$defaultLanguage}">{$condition/text()}</desc>
                                )
                            }
                            </condition>
                        ,
                        $concept/enableWhen,
                        $concept/terminologyAssociation,
                        $concept/addtionalAssociation,
                        $concept/identifierAssociation,
                        (: new in AD 3.10 - no real support, just make sure we don't loose it :)
                        $concept/containedTransaction
                    }
                    </concept>
            }
            </representingTemplate>
        </transaction>
    )
};

let $scenarioId             := request:get-parameter('id','')
let $scenarioEffectiveDate  := request:get-parameter('effectiveDate','')

let $transaction := 
    if (string-length($scenarioEffectiveDate) gt 0) then
        $get:colDecorData//transaction[@id=$scenarioId][@effectiveDate=$scenarioEffectiveDate]
    else (
        $get:colDecorData//transaction[@id=$scenarioId]
    )
let $defaultLanguage        := $transaction/ancestor::decor/project/@defaultLanguage

return
local:scenarioBasics($transaction, $defaultLanguage)

