<script>
    import { onMount } from 'svelte';
    import { t } from '../../translations.svelte.js';
    import { useTinyRouter } from 'svelte-tiny-router';
    import { user } from '../../user.svelte.js';

    const router = useTinyRouter();

    let users = $state([]);

    onMount(async () => {
        const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/list`;
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            const json = await resp.json();
            for (let u of json) users.push(u);
        }
    });

    async function impersonate(userId){
        const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/${userId}/impersonate`;
        const resp = await fetch(url,{
            method: 'POST',
            credentials: 'include'
        });
        if (resp.ok){
            const json = await resp.json();
            for (let key of Object.keys(json)) user[key] = json[key];
        }
    }

</script>

<fieldset tabindex="0">
    <legend>
        {t('list')}
        {#if user.permissions.includes('CREATE_USERS')}
        <button onclick={() => router.navigate('/user/create')}>{t('create_new')}</button>
        {/if}
    </legend>
    <table>
        <thead>
            <tr>
                <th>{t('id')}</th>
                <th>{t('name')}</th>
                <th>{t('email')}</th>
                <th>{t('language')}</th>
                <th>{t('actions')}</th>
            </tr>
        </thead>
        <tbody>
        {#each users as u,i}
            <tr>
                <td>{u.id}</td>
                <td>{u.name}</td>
                <td>{u.email}</td>
                <td>{u.language}</td>
                <td>
                    {#if user.permissions.includes('IMPERSONATE')}
                    <button onclick={() => impersonate(u.id)}>{t('impersonate')}</button>
                    {/if}
                    {#if user.permissions.includes('UPDATE_USERS')}
                    <button onclick={() => router.navigate(`/user/${u.id}/edit`)}>{t('edit')}</button>
                    {/if}
                </td>
            </tr>
        {/each}
        </tbody>
    </table>
</fieldset>