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";

let $datatypeType   := if (request:exists()) then request:get-parameter('type',())[1] else ()
let $datatypeType   := if (string-length($datatypeType) gt 0) then $datatypeType else 'hl7v3xml1'

let $decorDatatypes := $get:colDecorCore/supportedDataTypes[@type = $datatypeType]

return
<supportedDataTypes>
{
    $decorDatatypes/@*
}
{
    (:assume that if there is a definition for the dataType at root level, 
    then that is complete, whereas the sub typed dataType does not need to be:)
    for $type in distinct-values($decorDatatypes//dataType/@name | $decorDatatypes//flavor/@name | $decorDatatypes//atomicDataType/@name)
    let $typeDef    := 
        if ($decorDatatypes[@name=$type]) 
        then ($decorDatatypes[@name=$type])
        else ($decorDatatypes//dataType[@name = $type] | $decorDatatypes//flavor[@name = $type] | $decorDatatypes//atomicDataType[@name = $type])
    let $n1 := $type
    group by $n1
    order by $n1
    return
        <type>
        {$typeDef[1]/@name, $typeDef[1]/@type, $typeDef[1]/@hasStrength}
        {if ($typeDef[1][self::atomicDataType]) then attribute type {'simpletype'} else ()}
        <item name="{$n1}"/>
        {
            for $subtype in ($typeDef[1]//dataType|$typeDef[1]//flavor|$typeDef[1]//atomicDataType)
            let $n2 := $subtype/@name
            group by $n2
            order by $n2
            return
            <item name="{$n2}"/>
        }
        {
            $typeDef[1]/attribute,
            $typeDef[1]/element
        }
        </type>
}
</supportedDataTypes>