<template>
    <div class="content-l">
        <Table columns="auto auto 1fr auto" :show-footer="users.data.length === 0" v-if="users.loading === false && users.data">
            <HeaderRow>
                <HeaderCell>E-Mail</HeaderCell>
                <HeaderCell>First Name</HeaderCell>
                <HeaderCell>Last Name</HeaderCell>
                <HeaderCell></HeaderCell>
            </HeaderRow>
            <ContentRow v-for="user in users.data" @click="useRouter().push('/realms/' + useRoute().params.realm_key + '/users/' + user.id)">
                <ContentCell>{{ user.email }}</ContentCell>
                <ContentCell>{{ user.firstname }}</ContentCell>
                <ContentCell>{{ user.lastname }}</ContentCell>
                <ContentCell style="padding: 0.25rem;">
                    <UiButton><UiIcon>edit</UiIcon></UiButton>
                    <UiButton @click.stop="deleteUser(user)"><UiIcon>delete</UiIcon></UiButton>
                </ContentCell>
            </ContentRow>
            <template #footer>
                <p>No users found.</p>
            </template>
        </Table>
        <div>
            <UiButton @click="addUser">Create</UiButton>
        </div>
    </div>
</template>

<script setup lang="ts">
import Table from "~/components/ui/table/Table.vue";
import {useGet} from "~/utils/HttpUtils";
import {User} from "~/user/User"
import HeaderRow from "~/components/ui/table/HeaderRow.vue";
import HeaderCell from "~/components/ui/table/HeaderCell.vue";
import ContentCell from "~/components/ui/table/ContentCell.vue";
import ContentRow from "~/components/ui/table/ContentRow.vue";
import {Popup, PopupSize, usePopup} from "~/components/ui/popup/Popup";
import UserDelete from "~/user/UserDelete.vue"
import UserAdd from "~/user/UserAdd.vue";

const realmKey = useRoute().params.realm_key;

const users = useGet<User[]>('/api/realms/' + realmKey + '/users');

function addUser()
{
    const callback = (user: User) => {
        if (users.value.data)
        {
            users.value.data.push(user);
        }
    };
    usePopup().open(Popup.component<User>(UserAdd).setConfig({ heading: 'Add User', size: PopupSize.MEDIUM, callback: callback }));
}

function deleteUser(user: User)
{
    const callback = () => {
        if (users.value.data)
        {
            users.value.data = users.value.data.filter(u => u !== user);
        }
    }
    usePopup().open(Popup.component<User>(UserDelete).setPayload(user).setConfig({ heading: 'Delete User', size: PopupSize.MEDIUM, callback: callback }));
}
</script>

<style scoped>

</style>