<?xml version="1.0" encoding="UTF-8"?>

<!-- Pattern for the attribute values validation and ordering -->
<sch:pattern id="ValidateValidAttributeValuesAgainstList" abstract="true" xmlns:sch="http://purl.oclc.org/dsdl/schematron">
    <sch:p id="ruleText">$rule</sch:p>
    <sch:p id="codeDesc">$code</sch:p>
    <sch:rule context="$context">
        <!-- Define variables -->             
        <sch:let name="dataFileElems" value="$curElems"/>
        <sch:let name="attrValues" value="$curAttr"/>
        <sch:let name="attrValueTokens" value="tokenize($attrValues,' ')"/>
        <sch:let name="capco" value="$capcoRestriction"/>
        
        
        <!-- Get the position of each client node relative to its position in the master list.  If the node is not found, return a -1 -->
        <sch:let name="orderNums" value="
            for $token in $attrValueTokens return 
            if ($dataFileElems[matches($token,concat('^',text(),'$'))]) then 
            count(($dataFileElems[matches($token,concat('^',text(),'$'))])/preceding::*) + 1
            else -1"/>
        
        <!-- Determine if the list has invalid values. If and only if it does, figure out which ones are invalids -->
        <sch:let name="hasInvalids" value="count(index-of($orderNums,-1)) > 0"/>            
        <sch:let name="invalidValues" value="
            if ($hasInvalids) then
            distinct-values(
            for $token in index-of($orderNums,-1) return
            $attrValueTokens[$token] 
            )
            else null
            "/>
        
        <!-- Determine if the list has duplicate values. If and only if it does, figure out which ones are duplicates -->
        <sch:let name="hasDups" value="count(distinct-values($attrValueTokens)) != count($attrValueTokens)"/>            
        <sch:let name="dupValues" value="
            if ($hasDups) then
            distinct-values(
            for $token in $attrValueTokens return
            if (count(index-of($attrValueTokens,$token)) > 1) then $attrValueTokens[index-of($attrValueTokens,$token)[1]] 
            else null
            )   
            else null
            "/>
        
        <!-- Execute tests --> 
        <sch:assert test="if(not($ISM_CAPCO_RESOURCE) and $capco) then 1 else not($hasInvalids)" flag="$errFlag_ValueNotFound"><sch:value-of select="$errMsg_ValueNotFound"/>
            Invalid value of [<sch:value-of select="$invalidValues"/>]</sch:assert>
        <sch:assert test="not($hasDups)" flag="undefined">Duplicate values found [<sch:value-of select="$dupValues"
        />] for [<sch:value-of select="$attrValueTokens"/>] </sch:assert>
    </sch:rule>
</sch:pattern>