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

declare namespace request  = "http://exist-db.org/xquery/request";
declare namespace response = "http://exist-db.org/xquery/response";
declare namespace datetime = "http://exist-db.org/xquery/datetime";

let $project        := if (request:exists()) then request:get-parameter('project',())[string-length() > 0] else ()
let $includebbr     := if (request:exists()) then request:get-parameter('includebbr','false')='true' else false()
(: limit to datasets actually in a scenario :)
let $scenariosonly  := if (request:exists()) then request:get-parameter('scenariosonly','false')='true' else false()
let $treetype       := if (request:exists()) then request:get-parameter('treetype',()) else ('v2')
let $language       := if (request:exists()) then request:get-parameter('language',()) else ()

let $datasetlist    := art:getDatasetList($project, (), $language[string-length() gt 0], $includebbr, $scenariosonly)

return
    if ($treetype = 'v2') then (
        <datasets>
        {
            $datasetlist/@*
            ,
            for $datasets in $datasetlist/dataset
            let $id     := $datasets/@id
            group by $id
            order by if ($datasets[1]/name[@language = $language]) then $datasets[1]/name[@language = $language] else $datasets[1]/name[1], $datasets[1]/@effectiveDate descending, $datasets[1]/@versionLabel
            return
                element {$datasets[1]/name()} {
                    $datasets[1]/@id,
                    attribute uuid {util:uuid()}
                    ,
                    for $dataset in $datasets
                    let $ed     := $dataset/@effectiveDate
                    order by $ed descending
                    return
                        element {$dataset/name()} {
                            $dataset/@*,
                            attribute uuid {util:uuid()},
                            $dataset/node()
                        }
                }
        }
        </datasets>
    )
    else (
        $datasetlist
    )