xquery version "3.1";

(:
 : Copyright (c) 2018 Uwe Sikora
 : Copyright (c) 2018–2019 Michelle Weidling
 : Copyright (c) 2020 Stefan Hynek
 :
 : This file is part of intermediate-format.
 :
 : intermediate-format is free software: you can redistribute it and/or modify
 : it under the terms of the GNU General Public License as published by
 : the Free Software Foundation, either version 3 of the License, or
 : (at your option) any later version.
 :
 : intermediate-format is distributed in the hope that it will be useful,
 : but WITHOUT ANY WARRANTY; without even the implied warranty of
 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 : GNU General Public License for more details.
 :
 : You should have received a copy of the GNU General Public License
 : along with intermediate-format.  If not, see <https://www.gnu.org/licenses/>.
 :)

(:~
 : This is the main XQuery which will (by default) be called by controller.xql
 : to process any URI ending with ".html". It receives the HTML from
 : the controller and passes it to the templating system.
 :)

import module namespace templates="http://exist-db.org/xquery/templates" ;

(:
 : The following modules provide functions which will be called by the
 : templating.
 :)
import module namespace config="http://bdn-edition.de/intermediate_format/config" at "config.xqm";
import module namespace app="http://bdn-edition.de/intermediate_format/templates" at "app.xql";

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

declare option output:method "html5";
declare option output:media-type "text/html";

let $config := map {
    $templates:CONFIG_APP_ROOT : $config:app-root,
    $templates:CONFIG_STOP_ON_ERROR : true()
}
(:
 : We have to provide a lookup function to templates:apply to help it
 : find functions in the imported application modules. The templates
 : module cannot see the application modules, but the inline function
 : below does see them.
 :)
let $lookup := function($functionName as xs:string, $arity as xs:int) {
    try {
        function-lookup(xs:QName($functionName), $arity)
    } catch * {
        ()
    }
}
(:
 : The HTML is passed in the request from the controller.
 : Run it through the templating system and return the result.
 :)
let $content := request:get-data()
return
    templates:apply($content, $lookup, (), $config)