xquery version "1.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.
:)

(:
   Xquery for creating new dataset concept
   Input:
   - datasetId    : dataset to insert concept into.
   - conceptType  : item/group
   - insertMode   : into/following
   - insertRef    : conceptId reference for insert
   - language     : language code for concept name
:)
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";
import module namespace decor           = "http://art-decor.org/ns/decor" at "../api/api-decor.xqm";
declare namespace request   = "http://exist-db.org/xquery/request";
declare namespace datetime  = "http://exist-db.org/xquery/datetime";

(: variables for request parameters :)
let $datasetId              := if (request:exists()) then request:get-parameter('datasetId',())[string-length()>0] else ()
let $datasetEffectiveDate   := if (request:exists()) then request:get-parameter('datasetEffectiveDate',())[string-length()>0] else ()
let $conceptBaseId          := if (request:exists()) then request:get-parameter('conceptBaseId',()) else ()
let $conceptType            := if (request:exists()) then request:get-parameter('conceptType','') else ()
let $insertMode             := if (request:exists()) then request:get-parameter('insertMode','') else ()
let $insertRef              := if (request:exists()) then request:get-parameter('insertRef',())[string-length()>0] else ()
let $insertFlexibility      := if (request:exists()) then request:get-parameter('insertFlexibility',())[string-length()>0] else ()
let $language               := if (request:exists()) then request:get-parameter('language',())[string-length()>0] else ()
(:
let $datasetId := '2.999.999.9977.77.1'
let $conceptType := 'item'
let $insertMode := 'into'
let $insertRef := '2.999.999.9977.77.2.20000'
let $language := 'nl-NL':)

(: check if dataset not final or deprecated ? (security):)
let $dataset                := art:getDataset($datasetId,$datasetEffectiveDate)
let $decor                  := $dataset/ancestor::decor
let $language               := if ($language) then $language else $decor/project/@defaultLanguage

(: Note: not protected from missing defaultBaseId for given type ... :)
let $baseId                 := if (string-length($conceptBaseId)=0) then decor:getDefaultBaseIdsP($decor, $decor:OBJECTTYPE-DATASETCONCEPT)/@id else ($conceptBaseId)

let $newId                  := decor:getNextAvailableIdP($decor, $decor:OBJECTTYPE-DATASETCONCEPT, $baseId)/@id

let $storedConcept          := $dataset//concept[@id = $insertRef][@effectiveDate = $insertFlexibility][not(ancestor::history)]
let $now                    := substring(string(current-dateTime()), 1, 19)
let $concept                :=
    <concept type="{$conceptType}" id="{$newId}" effectiveDate="{$now}" statusCode="new" lastModifiedDate="{$now}">
        <name language="{$language}"/>
    </concept>
let $insert                 :=
    if ($storedConcept) then
        if ($insertMode='following') then
            update insert $concept following $storedConcept
        else
        if ($storedConcept[history | concept]) then
            update insert $concept preceding ($storedConcept/history | $storedConcept/concept)[1]
        else (
            update insert $concept into $storedConcept
        )
    else
    if (empty($insertRef)) then
        if ($dataset) then
            if ($dataset[concept]) then 
                update insert $concept following $dataset/concept[last()]
            else (
                update insert $concept into $dataset
            )
        else (
            error(QName('http://art-decor.org/ns/error', 'InconsistentConcept'), concat('Dataset id=''',$datasetId,''' and effectiveDate=''',$datasetEffectiveDate,''' does not exist. Don''t know where to insert'))
        )
    else (
        error(QName('http://art-decor.org/ns/error', 'InconsistentConcept'), concat('Dataset was found but concept id=''',$insertRef,''' and effectiveDate=''',$insertFlexibility,''' does not exist. Don''t know where to insert'))
    )

return
    <concept navkey="{util:uuid()}">{$concept/@* , $concept/node()}</concept>