<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2024 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<objectTemplate xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
                xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
                oid="d3f48222-63ff-4c9b-bcfa-e06903045b26">
    <name>Default role template</name>

    <mapping>
        <name>compute-membersCount</name>
        <documentation>Computes number of members of the role.</documentation>
        <strength>strong</strength>
<!-- channels can be defined to optimize recomputation when mapping is triggered -->
<!--        <channel>http://midpoint.evolveum.com/xml/ns/public/common/channels-3#recompute</channel>-->
<!--        <channel>http://midpoint.evolveum.com/xml/ns/public/common/channels-3#user</channel>-->
        <expression>
            <script>
                <relativityMode>absolute</relativityMode>
                <code>
                    import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType
                    import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType
                    import com.evolveum.midpoint.xml.ns._public.common.common_3.*

                    RoleType role = focus as RoleType

                    if (role == null) {
                        return 0
                    }
                    // Performs query for searching of all users having this role assigned DIRECTLY or INDIRECTLY
                    String roleOid = role.getOid()
                    //String queryStr = "assignment/targetRef matches (oid = '${roleOid}' )"
                    String queryStr = "roleMembershipRef matches (oid = '${roleOid}' )"

                    def query = midpoint.queryFor(UserType.class, queryStr)
                    def result = midpoint.searchObjects(query)
                    return result?.size()
                </code>
            </script>
        </expression>
        <target>
            <path>extension/membersCount</path>
        </target>
    </mapping>


    <!-- make custom attributes read-only -->
    <item>
        <ref>extension/membersCount</ref>
        <limitations>
            <layer>presentation</layer>
            <access>
                <read>true</read>
                <add>false</add>
                <modify>false</modify>
            </access>
        </limitations>
    </item>

</objectTemplate>