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

let $projectPrefix  := if (request:exists()) then request:get-parameter('project',())[string-length()>0] else ()
let $decor          := if (empty($projectPrefix)) then () else art:getDecorByPrefix($projectPrefix)
let $defaultLang    := $decor/project/@defaultLanguage
let $language       := if (request:exists()) then request:get-parameter('language',$defaultLang)[string-length()>0] else ($defaultLang)

return
    <ids>
    {
        (:
        Add empty designation for language, otherwise you cannot edit the designation in the project form. TODO: fix empty designations before/on save 
        <id root="1.0.639.2">
            <designation language="nl-NL" type="" displayName="ISO-639-2 Alpha 3" lastTranslated="" mimeType="">ISO-639-2 Alpha 3 Language</designation>
        </id>
        :)
        (:
            Old style:
                <baseId id="1.2.3" type="DS" prefix="xyz"/>
                <defaultBaseId id="1.2.3" type="DS"/>
            New style:
                <baseId id="1.2.3" type="DS" prefix="xyz" default="true"/>
                
            Rewrite old style to new style.
        :)
        for $baseId in $decor/ids/baseId
        return
            <baseId>
            {
                $baseId/@*
                ,
                if ($baseId[@default]) then () else (
                    attribute default {$decor//defaultBaseId/@id = $baseId/@id}
                )
            }
            </baseId>
        ,
        (: For now: keep old style so we can fix all dependent code later :)
        $decor/ids/defaultBaseId,
        for $identifier in $decor/ids/id
        return
            <id>
            {
                $identifier/@*,
                for $designation in $identifier/designation
                return
                    <designation language="{$designation/@language}" type="{$designation/@type}" displayName="{$designation/@displayName}">
                    {$designation/@lastTranslated, $designation/@mimeType, $designation/node()}
                    </designation>
                ,
                for $property in $identifier/property
                return
                    <property name="{$property/@name}">{$property/node()}</property>
            }
            </id>
    }
    </ids>