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";
import module namespace adsearch        = "http://art-decor.org/ns/decor/search" at "../api/api-decor-search.xqm";
import module namespace adserver        = "http://art-decor.org/ns/art-decor-server" at "..//api/api-server-settings.xqm";

let $searchTerms                := if (request:exists()) then tokenize(lower-case(request:get-parameter('searchString',())),'\s') else ('lich')
let $projectPrefix              := if (request:exists()) then (request:get-parameter('project',())) else ('demo1-')
(:normally we only want repository templates, but when we are looking for a prototype, we want to include templates from our own project:)
let $includeLocal               := if (request:exists()) then (request:get-parameter('includelocal','false')='true') else (true())

(:let $searchString := 'gend'
let $prefix :='demo1-':)

let $decor                      := $get:colDecorData//decor[project/@prefix=$projectPrefix]

let $schemaTypes                := art:getDecorTypes()//TemplateTypes/enumeration

(:
    <repositoryTemplateList url="http://art-decor.org/decor/services/" ident="ad1bbr-">
        <rules>
            <result current="50" total="50">
                <template id="2.16.840.1.113883.10.12.301">
                    <template name="CDAAct" displayName="CDA Act" isClosed="false" expirationDate="" officialReleaseDate="" id="2.16.840.1.113883.10.12.301" statusCode="active" versionLabel="" effectiveDate="2005-09-07T00:00:00" sortname="CDA Act">
                        <desc language="en-US">Template CDA Act (prototype, directly derived from POCD_RM000040 MIF)</desc>
                        <desc language="nl-NL">Template CDA Act (prototype, direct afgeleid uit POCD_RM000040 MIF)</desc>
                        <desc language="de-DE">Template CDA Act (Prototyp, direkt abgeleitet aus POCD_RM000040 MIF)</desc>
                        <desc language="pl-PL">&lt;font color="grey"&gt;&lt;i&gt;Description only available in other languages&lt;/i&gt;&lt;br /&gt;en-US: Template CDA Act (prototype, directly derived from POCD_RM000040 MIF)&lt;/font&gt;</desc>
                        <classification type="cdaentrylevel"/>
                    </template>
                </template>
            </result>
        </rules>
    </repositoryTemplateList>
:)
let $buildingBlockRepositories  := 
    if ($includeLocal) then (
        $decor/project/buildingBlockRepository[empty(@format)] | 
        $decor/project/buildingBlockRepository[@format='decor'] | 
        <buildingBlockRepository url="{adserver:getServerURLServices()}" ident="{$projectPrefix}" format="decor"/>
    )
    else (
        $decor/project/buildingBlockRepository[empty(@format)] | 
        $decor/project/buildingBlockRepository[@format='decor']
    )
let $result := 
    for $repository in $buildingBlockRepositories
    return
    <repositoryTemplateList url="{$repository/@url}" ident="{$repository/@ident}">
    {
        templ:getRepositoryAndBBRTemplateList($searchTerms, $repository/@ident)
    }
    </repositoryTemplateList>

return
    <result count="{count($result//template[template])}" search="{$searchTerms}" includelocal="{$includeLocal}">
    {
        (:get templates with and without classification:)
        for $clt in (distinct-values($result//classification/@type),if ($result//template[template[empty(classification/@type)]]) then '' else ())
        let $type := if ($clt='') then 'notype' else $clt
        group by $type
        order by count($schemaTypes[@value=$type]/preceding-sibling::enumeration)
        return
        <class uuid="{util:uuid()}" type="{$type}">
        {
            for $label in $schemaTypes[@value=$type]/label
            return
                <label language="{$label/@language}">{$label/text()}</label>
        }
        {
            let $templateSet := 
                if ($clt='') then
                    $result//template[template[empty(classification/@type)]]
                else (
                    $result//template[template/classification[@type=$type]]
                )
            for $r in $templateSet
            let $fromRepository := $r/ancestor::repositoryTemplateList/@ident
            return
                <template>
                {
                    $r/@*,
                    if ($r/@uuid) then () else attribute uuid {util:uuid($r)},
                    if ($r/@fromRepository) then () else attribute fromRepository {$fromRepository},
                    for $t in $r/template
                    let $alreadyrefed := count($decor/rules/template[@ref=$t/@id]) > 0
                    order by $t/@effectiveDate descending
                    return
                        <template>
                        {
                            $t/@*,
                            if ($t/@uuid) then () else attribute uuid {util:uuid($t)},
                            if ($alreadyrefed) then attribute alreadyrefed {'true'} else (),
                            $t/*
                        }
                        </template>
                }
                </template>
        }
        </class>
    }
    </result>