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 xforms            = "http://www.w3.org/2002/xforms";
declare namespace xsl               = "http://www.w3.org/1999/XSL/Transform";

declare %private function local:getMatches($input as xs:string?, $output as xs:string*) as xs:string* {
    let $match := replace($input,'.*\$resources/([A-Za-z0-9_\-]+).*','$1')
    
    return
        if (string-length($match) gt 0) then
            if ($match = $input) then $output else (
                local:getMatches(replace($input,concat('\$resources/',$match),''),($output,$match))
            )
        else ($output)
};

let $packageRoot    := if (request:exists()) then request:get-parameter('packageRoot','art') else 'art'

(: put all xform resources in variable:)
let $all-form-resources :=
    for $key in distinct-values(
        (
           (collection(concat($get:root,$packageRoot,'/xforms'))//*[contains(@ref,'$resources/')]/@ref | 
            collection(concat($get:root,$packageRoot,'/xforms'))//*[contains(@title,'$resources/')]/@title |
            collection(concat($get:root,$packageRoot,'/xforms'))//*[contains(@value,'$resources/')]/@value |
            collection(concat($get:root,$packageRoot,'/resources/stylesheets'))//xsl:attribute[contains(.,'$resources/')])
            ,
            if ($packageRoot = 'art') then (collection(concat($get:strArtData,'/resources'))//menu//@label/concat('$resources/',.)) else ()
        )
    )
    return
        local:getMatches($key,())

(: existing resources:)
let $artXformResources  := art:getFormResources($packageRoot)

(: list of all keys:)
let $keys               := distinct-values($artXformResources/resources/*/name())
let $keyMap             := map:merge(for $key in $keys return map:entry($key, true()))

(: check if resource exists, if not generate empty text elements for each language in resources:)
return
<undefinedResources packageRoot="{$packageRoot}">
{
    for $undefined-resource in distinct-values($all-form-resources)
    order by lower-case($undefined-resource)
    return
        if (map:contains($keyMap, $undefined-resource)) then () else (
            <resource key="{$undefined-resource}">
            {
                for $resource in $artXformResources/resources
                return
                <text xml:lang="{$resource/@xml:lang}" displayName="{$resource/@displayName}"/>
            }
            </resource>
        )
}
</undefinedResources>