xquery version "3.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 option exist:serialize "indent=yes";
declare option exist:serialize "omit-xml-declaration=no";

let $projectPrefix          := if (request:exists()) then request:get-parameter('project','') else ('demo1-')
let $decor                  := $get:colDecorData//decor[project/@prefix=$projectPrefix]

let $projectChecks          := collection(get:strProjectDevelopment($projectPrefix))//@optionalChecks[1]

let $optionalCheckFile      := concat($get:strDecorCore, '/DECOR-optional-checks.sch')
let $optionalChecks         := if (fn:doc-available($optionalCheckFile)) then doc($optionalCheckFile) else ()
let $projectSchematronFile  := concat(get:strProjectDevelopment($projectPrefix), $projectPrefix, 'checks.sch')
let $projectSchematron      := if (fn:doc-available($projectSchematronFile)) then doc($projectSchematronFile) else ()
let $checks                 := tokenize($projectChecks, ' ')
let $result :=
    if ($optionalChecks)
    then
        (: Note that what's sent to XForm is not real schematron, just id's and titles :)
        <checks xmlns:sch="http://purl.oclc.org/dsdl/schematron">
            {
            for $pattern in $optionalChecks//sch:pattern
            return
                <pattern id="{$pattern/@id}" on="{if ($pattern/@id = $checks) then true() else false()}">
                    <title>{$pattern/sch:title/text()}</title>
                </pattern>
            }
            {
            for $pattern in $projectSchematron//sch:pattern
            return
                <pattern on="true" readonly="true">
                    <title>{$pattern/sch:title/text()}</title>
                </pattern>
            }
        </checks>
    else <checks/>


return
if ($projectPrefix= '') then (
    if (response:exists()) then (response:set-status-code(404), response:set-header('Content-Type','text/xml; charset=utf-8')) else (), 
    <error>Missing parameter 'prefix'</error>
)
else (
    if (response:exists()) then (response:set-header('Content-Type','text/xml; charset=utf-8')) else (),
    $result
)