<template>
    <form class="content-l" @submit.prevent="assign(selection)" v-if="roles && roles.length > 0">
        <div class="content-m">
            <p class="tile-m role left-center" :class="{ selected: selection?.name === role.name }" v-for="role in roles" @click="selection = role">{{ role.name }}</p>
        </div>
        <div class="center">
            <UiButton type="submit" :disabled="selection == null">Assign</UiButton>
        </div>
    </form>
    <div v-else>
        <p class="tile-m">There are no roles available for assignment.</p>
    </div>
</template>

<script setup lang="ts">
import type {Role} from "~/role/Role";
import {usePopup} from "~/components/ui/popup/Popup";
import {usePost, usePut} from "~/utils/HttpUtils";

const selection: Ref<Role | undefined> = ref();

const roles = usePopup().require<Role[]>().payload;

function assign(role?: Role)
{
    if (role != null)
    {
        const realmKey = useRoute().params.realm_key;
        const userId = useRoute().params.user_id;
        usePut<any, { assign: string[] }>("/api/realms/" + realmKey + "/users/" + userId + "/role-assignments", { assign: [role.name]}, () => {
            usePopup().callback(role);
            usePopup().close();
        })
    }
}
</script>

<style scoped>
.role {
    height: 2.5rem;
    border: 2px solid transparent;
}
.selected {
    border-color: black;
}
</style>