xquery version "3.1";

(:
 : This module handles calls to the API on manifest level, e.g.
 :
 : /textapi/ahiqar/arabic/3rx15/manifest.json
 :)

module namespace tapi-mani="http://ahiqar.uni-goettingen.de/ns/tapi/manifest";

declare namespace tei="http://www.tei-c.org/ns/1.0";
declare namespace tgmd="http://textgrid.info/namespaces/metadata/core/2010";

import module namespace commons="http://ahiqar.uni-goettingen.de/ns/commons" at "commons.xqm";


declare function tapi-mani:get-json($collection-type as xs:string,
    $manifest-uri as xs:string,
    $server as xs:string)
as map() {
    commons:validate-rest-input($collection-type, $manifest-uri, ()),
    let $tei-xml := commons:get-tei-xml-for-manifest($manifest-uri)
    return
        map {
            "@context": "https://gitlab.gwdg.de/subugoe/emo/text-api/-/raw/main/jsonld/manifest.jsonld",
            "textapi": $commons:textapi-version,
            "x-app-version": $commons:version,
            "id": $server || "/" || $commons:api-prefix || $collection-type || "/" || $manifest-uri || "/manifest.json",
            "label": tapi-mani:get-manifest-title($manifest-uri),
            "metadata":
                (: for the Salhani print which has slightly different metadata :)
                if ($manifest-uri = "3rx14") then
                    tapi-mani:make-metadata-objects-for-Salhani($tei-xml, $server)
                (: for the rest of the manuscripts :)
                else
                    tapi-mani:make-metadata-objects($tei-xml, $server, $manifest-uri),
            "support": tapi-mani:make-support-object($server),
            "license": tapi-mani:get-license-info($tei-xml),
            "annotationCollection": $server || "/" || $commons:annotation-prefix || $collection-type || "/" || $manifest-uri || "/annotationCollection.json",
            "sequence": array{ tapi-mani:make-sequences($collection-type, $manifest-uri, $server) },
            "actor": array{ tapi-mani:make-editors($tei-xml) }
        }
};

declare function tapi-mani:get-manifest-title($manifest-uri as xs:string)
as xs:string {
    let $metadata-file := commons:get-metadata-file($manifest-uri)
    return
        $metadata-file//tgmd:title/string()
};

declare function tapi-mani:make-metadata-objects($tei-xml as document-node(),
    $server as xs:string,
    $manifest-uri as xs:string)
as map()+ {
    tapi-mani:make-creation-date($tei-xml),
    tapi-mani:make-origin($tei-xml),
    tapi-mani:make-current-location($tei-xml),
    tapi-mani:make-url-to-tei($tei-xml/base-uri(), $server),
    tapi-mani:make-citation-hints($tei-xml, $manifest-uri),
    (: the audio testimonies :)
    if ($tei-xml//tei:recordingStmt) then
        (map {
            "key": "Source of the audio files",
            "value": $tei-xml//tei:recordingStmt//tei:media
            },
        map {
            "key": "License of the audio files",
            "value": $tei-xml//tei:recordingStmt/tei:p[@n = 'license']/text()
            })
    else
        ()
};

declare function tapi-mani:make-citation-hints($tei-xml as document-node(),
    $manifest-uri as xs:string)
as map() {
    let $editors := $tei-xml//tei:titleStmt/tei:editor
    let $_editor-string := for $editor in $editors return
        let $tokens := tokenize($editor, " ")
        let $lastname := $tokens[last()]
        let $_rest := replace($editor, $lastname, "")
        let $rest := replace($_rest, "Dr. ", "")
        return concat($lastname, ", ", normalize-space($rest))

    (: This yields in something like
       Birol, Simon, Sims-Williams, Nicolas :)
    let $editor-string := string-join($_editor-string, ", ")
    let $lang-short := $tei-xml//tei:text[@type = "transcription"]/@xml:lang
    let $_lang := $tei-xml//tei:language[@ident = $lang-short]/text()

    let $lang := if ($_lang) then
        $_lang
    else
        if ($lang-short/string() = "sogdian") then
            "Sogdian"
        else
            "blubb"

    let $ms-name := commons:get-metadata-file($manifest-uri)//tgmd:title/text()
    let $today := util:system-date() => replace("Z", "") => tokenize("-")
    let $year := $today[1]
    let $month := $today[2]
    let $day :=$today[3]
    let $date := string-join(($day, $month, $year), ".")
    let $link := "https://ahiqar.uni-goettingen.de/" || lower-case(tokenize($lang)[last()]) || ".html"

    (: example:
(:    Birol, Simon. „Textual witnesses in Syriac. Paris, Bibliothèque nationale de France, Ms. syr. 434.“. :)
(:    Ahiqar. The Story of Ahiqar in Its Syriac and Arabic Tradition,:)
(:    15. Oktober 2021, . https://ahiqar.uni-goettingen.de/syriac.html:):)
    let $cit-str := $editor-string
        || '. "Textual witnesses in ' || $lang || '. '
        || $ms-name || '." Ahiqar. The Story of Ahiqar in Its Syriac and Arabic Tradition, ' ||
        $date || ', ' || $link

    return
        map {
            "key": "Citation",
            "value": $cit-str
        }
};

declare function tapi-mani:make-sequences($collection-type as xs:string,
    $manifest-uri as xs:string,
    $server as xs:string)
as map()+ {
    let $valid-pages := commons:get-valid-page-ids($manifest-uri)
    return
            for $page in $valid-pages
            let $uri := $commons:api-prefix || $collection-type || "/" || $manifest-uri || "/" ||  commons:format-page-number($page) || "/latest/item.json"
            return
                map {
                    "@context": "https://gitlab.gwdg.de/subugoe/emo/text-api/-/raw/main/jsonld/sequence.jsonld",
                    "id": $server || "/" || $uri,
                    "label": $page,
                    "type": "item"
                }
};


declare function tapi-mani:make-editors($tei-xml as document-node())
as map()* {
    let $editors := $tei-xml//tei:titleStmt//tei:editor
    for $editor in $editors return
        map {
            "@context": "https://gitlab.gwdg.de/subugoe/emo/text-api/-/raw/main/jsonld/actor.jsonld",
            "role": array { "editor" },
            "name": $editor/string()
        }
};

declare function tapi-mani:make-creation-date($tei-xml as document-node())
as map() {
    let $creation-date := $tei-xml//tei:history//tei:date
    let $string :=
        if ($creation-date) then
            $creation-date/string()
        else
            "unknown"
    return
        map {
            "key": "Date of creation",
            "value": $string
        }
};

declare function tapi-mani:make-origin($tei-xml as document-node())
as map() {
    let $country := $tei-xml//tei:history//tei:country
    let $place := $tei-xml//tei:history//tei:placeName
    let $string :=
        if ($country and $place) then
            $place/string() || ", " || $country/string()
        else if ($country) then
            $country/string()
        else if($place) then
            $place/string()
        else
            "unknown"
    return
        map {
            "key": "Place of origin",
            "value": $string
        }
};

declare function tapi-mani:make-current-location($tei-xml as document-node())
as map() {
    let $institution := $tei-xml//tei:msIdentifier//tei:institution
    let $country := $tei-xml//tei:msIdentifier//tei:country
    let $string :=
        if ($country and $institution) then
            $institution || ", " || $country
        else if ($country) then
            $country/string()
        else if($institution) then
            $institution/string()
        else
            "unknown"
    return
        map {
            "key": "Current location",
            "value": $string
        }
};

declare function tapi-mani:make-url-to-tei($uri as xs:anyURI, $server as xs:string)
as map() {
    map {
            "key": "TEI document",
            "value": "[via REST](" || $server || "/rest/textgrid/" || substring-after($uri, "textgrid/") || ")"
        }
};

declare function tapi-mani:get-license-info($tei-xml as document-node())
as array(*) {
    array {
        map {
            "@context": "https://gitlab.gwdg.de/subugoe/emo/text-api/-/raw/main/jsonld/license.jsonld",
            "id":
                    let $target := $tei-xml//tei:licence/@target
                    return
                        if ($target = "https://creativecommons.org/licenses/by-sa/4.0/") then
                            "[CC-BY-SA-4.0](https://creativecommons.org/licenses/by-sa/4.0/legalcode)"
                        else
                            "no license provided"
        }
    }
};

declare function tapi-mani:make-support-object($server as xs:string)
as array(*) {
    array {
        map {
            "@context": "https://gitlab.gwdg.de/subugoe/emo/text-api/-/raw/main/jsonld/support.jsonld",
            "type": "css",
            "mime": "text/css",
            "url": $server || "/content/ahiqar.css"
        },
        tapi-mani:make-fonts($server)
    }
};

declare function tapi-mani:make-fonts($server as xs:string)
as map(*)+ {
    for $uri in xmldb:get-child-resources("/db/data/resources/fonts") return
        map {
            "@context": "https://gitlab.gwdg.de/subugoe/emo/text-api/-/raw/main/jsonld/support.jsonld",
            "type": "font",
            "mime": "font/woff",
            "url": $server || "/content/" || $uri
        }
};

declare function tapi-mani:make-metadata-objects-for-Salhani($tei-xml as document-node(), $server as xs:string)
as map()+ {
    map {
        "key": "Title of the edited chapter",
        "value": $tei-xml//tei:biblStruct//tei:title[@level = "a"]/string()
    },
    map {
        "key": "Part of",
        "value":
            (: author :)
            $tei-xml//tei:biblStruct/tei:monogr/tei:editor || ". " ||
            (: title :)
            $tei-xml//tei:biblStruct/tei:monogr/tei:title[@type = "main"] || " (" ||
            $tei-xml//tei:biblStruct/tei:monogr/tei:title[@type = "alt"] || "). " ||
            (: publication place and date :)
            $tei-xml//tei:biblStruct/tei:monogr//tei:pubPlace || " " ||
            $tei-xml//tei:biblStruct/tei:monogr//tei:date || ", " ||
            (: pages :)
            $tei-xml//tei:biblStruct/tei:monogr//tei:biblScope || ". " ||
            (: publisher :)
            "Published by " || $tei-xml//tei:biblStruct/tei:monogr//tei:publisher || "."
    },
    tapi-mani:make-url-to-tei($tei-xml/base-uri(), $server)
};
