xquery version "3.1";

(:~
 : Giving specific structural information on database content.
 :
 : @author Mathias Göbel
 : @version 0.1.0
 : @since 12.1.0
 :)

module namespace structure="http://ahiqar.uni-goettingen.de/ns/structure";
import module namespace commons="http://ahiqar.uni-goettingen.de/ns/commons" at "/db/apps/ahiqar/modules/commons.xqm";
import module namespace rest="http://exquery.org/ns/restxq";

declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization";
declare namespace tei="http://www.tei-c.org/ns/1.0";

(:~
 : Create a list of tei:milestone elements mapped together with useful metadata.
 : @return map(*)
 :  :)
declare
  %rest:GET
  %rest:HEAD
  %rest:path("/structure")
  %rest:produces("application/json")
  %output:method("json")
function structure:main()
as map(*)*{ 

for $text in collection( $commons:data )//tei:text
let $baseUri := $text/base-uri()
where not( contains($baseUri, "sample") )
order by $baseUri
return
    map{
        "doc": $baseUri,
        "attributes": array{ for $attrib in $text/@* return map{local-name($attrib): string($attrib)}},
        "idnos" : $text/ancestor::tei:TEI//tei:idno/string(),
        "milestones": array{
            for $milestone in $text//tei:milestone[@unit]
            return
                string($milestone/@unit)
            }
        }  
};
