xquery version "3.1";

module namespace sh="http://ahiqar.uni-goettingen.de/ns/tapi/html/save";

import module namespace commons="http://ahiqar.uni-goettingen.de/ns/commons" at "/db/apps/ahiqar/modules/commons.xqm";
import module namespace tapi-html="http://ahiqar.uni-goettingen.de/ns/tapi/html" at "/db/apps/ahiqar/modules/tapi-html.xqm";

declare namespace tei="http://www.tei-c.org/ns/1.0";

declare function sh:prepare-unit-tests($fragments as element())
as item()+ {
    let $uris :=
        for $uri in xmldb:get-child-resources($commons:data)[ends-with(., ".xml")] return
            $commons:data || $uri

    for $uri in $uris return
        sh:save-html($uri, $fragments)
};


declare function sh:save-html($teixml-uri as xs:string,
    $fragments as element()) {
    util:log("INFO", "Recreate HTML files for TEI file " || $teixml-uri),
    let $text-types := distinct-values($fragments/page/@type/string())
    for $type in $text-types return
        for $page in $fragments/page[@type = $type] return
            let $html := tapi-html:get-html($teixml-uri, $page/@n, $page/tei:TEI, $type)
            let $filename := sh:make-filename($teixml-uri, $page/@n, $type)
            let $store := xmldb:store($commons:html, $filename, $html)
            return
                util:log("INFO", "Stored HTML files for TEI file " || $teixml-uri || ", page " || $page/@n)
};

declare function sh:make-filename($teixml-uri as xs:string,
    $page as xs:string,
    $type as xs:string)
as xs:string {
    $teixml-uri || "-" || commons:format-page-number($page) || "-" || $type || ".html"
};
