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 "xmldb:exist:///db/apps/art/modules/art-decor-settings.xqm";
(:import module namespace get ="http://art-decor.org/ns/art-decor-settings" at "art-decor-settings.xqm";:)
(:import module namespace get ="http://art-decor.org/ns/art-decor-settings" at "../../../modules/art-decor-settings.xqm";:)
declare namespace expath    = "http://expath.org/ns/pkg";

declare %private function local:cleanupTerminologyName($s as xs:string?) as xs:string? {
    if (empty($s)) then () else (
        replace(replace($s,'\s*[Tt]erminology\s*[Ds]ata\s*-\s*',''),' [Dd]ata$','')
    )
};

(: all terminology data collections :)
let $newTerminologyCollections :=('codesystem-stable-data','codesystem-authoring-data','conceptmap-authoring-data','conceptmap-stable-data','valueset-authoring-data','valueset-stable-data','nictiz-demo-data')
let $collections        := if (xmldb:collection-available($get:strTerminologyData)) then xmldb:get-child-collections($get:strTerminologyData) else ()
let $classifications    :=
    <classifications>
    {
        for $child in $collections[not(.=$newTerminologyCollections)]
        let $colName        := concat($get:strTerminologyData,'/',$child)
        let $titles         := collection($colName)//ClaML/Title
        let $packageTitle   := local:cleanupTerminologyName(collection($colName)//expath:package/expath:title/text())
        order by lower-case($packageTitle)
        return
        if ($titles) then
            <classification collection="{$child}" displayName="{$packageTitle}">
            {
                for $title in $titles
                return
                <Title language="{substring-after(substring-before(util:collection-name($title),'/claml'),concat($get:strTerminologyData,'/',$child,'/'))}">
                {
                    $title/@*,
                    $title/text()
                }
                </Title>
            }
            </classification>
        else()
    }
    </classifications>
    
    let $packages :=
    <packages>
    {
        for $child in $collections[not(.=$newTerminologyCollections)]
        let $package    := collection(concat($get:strTerminologyData,'/',$child))//expath:package
        let $abbrev     := $package/@abbrev
        let $version    := $package/@version
        let $name       := local:cleanupTerminologyName($package/expath:title/text())
        order by $name
        return
            if (empty($package)) then () else (
                <package abbrev="{$abbrev}" version="{$version}">{$name}</package>
            )
    }
    </packages>

return
<terminology>
    {$classifications,$packages}
</terminology>