<template>
    <div class="content-m">
        <div class="left-center">
            <h3>Roles</h3>
            <UiButton class="small" icon="group_add" @click="assignRoles(roleAssignments.unassigned)" reverse>Assign</UiButton>
        </div>
        <Table columns="1fr auto" :show-footer="roleAssignments.assigned.length === 0">
            <HeaderRow>
                <HeaderCell>Name</HeaderCell>
                <HeaderCell></HeaderCell>
            </HeaderRow>
            <ContentRow v-for="role in roleAssignments.assigned">
                <ContentCell>{{role.name}}</ContentCell>
                <ContentCell style="padding: 0.25rem;" @click="unassign(role)"><UiButton icon="delete"></UiButton></ContentCell>
            </ContentRow>
            <template #footer>
                <p>No roles assigned.</p>
            </template>
        </Table>
    </div>
</template>

<script setup lang="ts">
import UiButton from "~/components/ui/UiButton.vue";
import Table from "~/components/ui/table/Table.vue";
import HeaderCell from "~/components/ui/table/HeaderCell.vue";
import ContentCell from "~/components/ui/table/ContentCell.vue";
import HeaderRow from "~/components/ui/table/HeaderRow.vue";
import ContentRow from "~/components/ui/table/ContentRow.vue";
import type {RoleAssignment} from "~/role-assignment/RoleAssignment";
import type {Role} from "~/role/Role";
import {Popup, PopupSize, usePopup} from "~/components/ui/popup/Popup";
import UserRoleAssignment from "~/user/UserRoleAssignment.vue";

const props = defineProps<{
    roleAssignments: RoleAssignment
}>()

function unassign(role: Role)
{
    const callback = (role: Role) => {
        props.roleAssignments.unassigned.push(role);
        const index = props.roleAssignments.assigned.findIndex(item => item.name === role.name);
        if (index >= 0)
        {
            props.roleAssignments.assigned.splice(index, 1);
        }
    }
    const realmKey = useRoute().params.realm_key;
    const userId = useRoute().params.user_id;
    usePut<any, { unassign: string[] }>("/api/realms/" + realmKey + "/users/" + userId + "/role-assignments", { unassign: [role.name] }, () => {
        callback(role);
    });
}

function assignRoles(unassignedRoles: Role[])
{
    const callback = (role: Role) => {
        props.roleAssignments.assigned.push(role);
        const index = props.roleAssignments.unassigned.findIndex(item => item.name === role.name);
        if (index >= 0)
        {
            props.roleAssignments.unassigned.splice(index, 1);
        }
    }
    usePopup().open(Popup.component<Role[]>(UserRoleAssignment).setPayload(unassignedRoles).setConfig({ heading: 'Assign Roles', size: PopupSize.MEDIUM, callback: callback }));
}
</script>

<style scoped>

</style>