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.
:)
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 %private function local:prepareProject($node as item()?) as item()? {
    if ($node instance of element()) then (
        if ($node[name()='decor']) then (
            element {$node/name()} {
                $node/@*[not(.='')],
                
                (: hack alert. This forces the serializer to write our 'foreign' namespace declarations. Reported on the exist list :)
                (: this part of the code needs to NullPointerException hence this part is deactivated because it is non essential :)
               (: for $ns-prefix at $i in in-scope-prefixes($node)[not(.=('xml'))]
                let $ns-uri := namespace-uri-for-prefix($ns-prefix, $node)
                return
                    attribute {QName($ns-uri,concat($ns-prefix,':dummy-',$i))} {$ns-uri},:)
                
                for $subnode in $node/node()
                return local:prepareProject($subnode)
            }
        )
        else if ($node[name()='desc']) then (
            art:parseNode($node)
        )
        else (
            element {$node/name()} {
                $node/@*[not(.='')],
                for $subnode in $node/node()
                return local:prepareProject($subnode)
            }
        )
    )
    else (
        $node
    )
};

let $package-navigation     := if (request:exists()) then request:get-parameter('package',()) else ('projects')
let $project-prefix         := if (request:exists()) then request:get-parameter('project',()) else ('testad2-')
let $project-data           := if (request:exists()) then request:get-data()/decor else (
(:<decor><project prefix="{$project-prefix}"/></decor>:)
<decor xmlns:cda="urn:hl7-org:v3" xmlns:hl7="urn:hl7-org:v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://assets.art-decor.org/ADAR/rv/DECOR.xsd" repository="false" private="false">
    <project id="2.16.840.1.113883.3.1937.99.99.909" prefix="{$project-prefix}" defaultLanguage="nl-NL" experimental="true">
        <name language="">testAD2</name>
        <desc language="">&lt;div&gt;Testen van simultaan editen ART-DECOR 2 &amp;amp; 3 - aanmaken nieuw project ad2&lt;/div&gt;</desc>
        <copyright by="Vanessa Braumüller" logo="" years="2021" type="author"/>
        <author id="1" username="admin" email="" notifier="off">Administrator</author><author xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:widget="http://orbeon.org/oxf/xml/widget" xmlns:f="http://orbeon.org/oxf/xml/formatting" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:atp="urn:nictiz.atp" xmlns:fr="http://orbeon.org/oxf/xml/form-runner" xmlns:xxforms="http://orbeon.org/oxf/xml/xforms" xmlns:xhtml="http://www.w3.org/1999/xhtml" id="2" username="aaa-project-admin" email="" notifier="off">aaa-project-admin</author>
        <reference url=""/>
        <defaultElementNamespace ns="hl7:"/>
    </project>
    <datasets>
        <dataset id="" effectiveDate="" statusCode="draft" lastModifiedDate="{substring(string(current-dateTime()), 1, 19)}">
            <name language="">testad2 dataset</name>
            <desc language="">&lt;div&gt;Testen van simultaan editen ART-DECOR 2 &amp;amp; 3 - aanmaken nieuw project ad2&lt;/div&gt;</desc>
            <concept id="" type="item" effectiveDate="" statusCode="draft" lastModifiedDate="{substring(string(current-dateTime()), 1, 19)}">
                <name language="">Concept 1</name>
                <desc language=""/>
                <valueDomain type="string"/>
            </concept>
        </dataset>
    </datasets>
    <scenarios>
        <actors/>
    </scenarios>
    <ids><!-- OID subbranches --><!-- data set -->
        <baseId id=".1" type="DS" prefix="dataset-"/><!-- data elementen -->
        <baseId id=".2" type="DE" prefix="dataelement-"/><!-- scenario's -->
        <baseId id=".3" type="SC" prefix="scenario-"/><!-- transactions -->
        <baseId id=".4" type="TR" prefix="transaction-"/><!-- codesystems -->
        <baseId id=".5" type="CS" prefix="codesystem-"/><!-- issues -->
        <baseId id=".6" type="IS" prefix="issue-"/><!-- actors -->
        <baseId id=".7" type="AC" prefix="actor-"/><!-- concept list -->
        <baseId id=".8" type="CL" prefix="conceptlist-"/><!-- template elements -->
        <baseId id=".9" type="EL" prefix="template-element-"/><!-- template elements -->
        <baseId id=".10" type="TM" prefix="template-"/><!-- value set elements -->
        <baseId id=".11" type="VS" prefix="valueset-"/><!-- rule-intern -->
        <baseId id=".16" type="RL" prefix="rule-intern-"/><!-- test transaction -->
        <baseId id=".17" type="TX" prefix="test-transaction-"/><!-- test scenario -->
        <baseId id=".18" type="SX" prefix="test-scenario-"/><!-- example instances -->
        <baseId id=".19" type="EX" prefix="example-instance-"/><!-- qualification-test instances -->
        <baseId id=".20" type="QX" prefix="qualification-test-instance-"/><!-- community -->
        <baseId id=".21" type="CM" prefix="community-"/><!-- concept map -->
        <baseId id=".24" type="MP" prefix="map-"/>
        <baseId id=".26" type="QQ" prefix="questionnaire-"/>
        <baseId id=".27" type="QR" prefix="questionnaireresponse-"/>
        <baseId id=".28" type="SD" prefix="structuredefinition-"/>
        <baseId id=".29" type="IG" prefix="implementationguide-"/>
        <!-- default base id's per DECOR type -->
        <defaultBaseId id=".1" type="DS"/>
        <defaultBaseId id=".2" type="DE"/>
        <defaultBaseId id=".3" type="SC"/>
        <defaultBaseId id=".4" type="TR"/>
        <defaultBaseId id=".5" type="CS"/>
        <defaultBaseId id=".6" type="IS"/>
        <defaultBaseId id=".7" type="AC"/>
        <defaultBaseId id=".8" type="CL"/>
        <defaultBaseId id=".9" type="EL"/>
        <defaultBaseId id=".10" type="TM"/>
        <defaultBaseId id=".11" type="VS"/>
        <defaultBaseId id=".16" type="RL"/>
        <defaultBaseId id=".17" type="TX"/>
        <defaultBaseId id=".18" type="SX"/>
        <defaultBaseId id=".19" type="EX"/>
        <defaultBaseId id=".20" type="QX"/>
        <defaultBaseId id=".21" type="CM"/>
        <defaultBaseId id=".24" type="MP"/>
        <defaultBaseId id=".26" type="QQ"/>
        <defaultBaseId id=".27" type="QR"/>
        <defaultBaseId id=".28" type="SD"/>
        <defaultBaseId id=".29" type="IG"/>
    </ids>
    <terminology/>
    <rules/>
    <issues notifier="on"/>
</decor>
)
(:let $project-prefix         := ($project-data/project/@prefix/string())[1]:)

let $projectStoreParent     := concat($get:strDecorData,'/',$package-navigation)
let $projectStoreResource   := concat($project-prefix,'decor.xml')
let $projectStoreCollection := substring($project-prefix,1,string-length($project-prefix)-1)
let $projectLogosCollection := concat($project-prefix,'logos')

let $project-data           := 
    document {
        processing-instruction {'xml-model'} {' href="https://assets.art-decor.org/ADAR/rv/DECOR.sch" type="application/xml" schematypens="http://purl.oclc.org/dsdl/schematron"'},
        processing-instruction {'xml-stylesheet'} {' type="text/xsl" href="https://assets.art-decor.org/ADAR/rv/DECOR2schematron.xsl"'},
        for $node in $project-data return local:prepareProject($node) 
    }

let $data-safe :=
    if (empty($project-prefix)) then
        'Project has no prefix in /decor/project/@prefix'
    else if (not(xmldb:collection-available($projectStoreParent))) then
        concat('Package collection does not exist: ',$projectStoreParent)
    else if (xmldb:collection-available(concat($projectStoreParent,'/',$projectStoreCollection))) then
        concat('Project collection already exists: ',$projectStoreCollection)
    else if (not(sm:has-access($projectStoreParent,'rwx'))) then
        concat('Current user has no write privileges: ',get:strCurrentUserName())
    else (
        let $create-parent  := xmldb:create-collection($projectStoreParent,$projectStoreCollection)
        let $parent-chown   := sm:chown(xs:anyURI($create-parent),'admin:decor')
        let $parent-chmod   := sm:chmod(xs:anyURI($create-parent),'rwxrwxr-x')
        
        let $create-logos   := xmldb:create-collection($create-parent,$projectLogosCollection)
        let $logos-chown    := sm:chown(xs:anyURI($create-logos),'admin:decor')
        let $logos-chmod    := sm:chmod(xs:anyURI($create-logos),'rwxrwxr-x')
        
        let $create-project := xmldb:store($create-parent,$projectStoreResource,$project-data)
        let $project-chown  := sm:chown(xs:anyURI($create-project),'admin:decor')
        let $project-chmod  := sm:chmod(xs:anyURI($create-project),'rw-rw-r--')
        
        return ()
    )
    
return
    <data-safe error="{$data-safe}">{empty($project-data)}</data-safe>
