<script>
    import { onMount }       from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';

    import { api }           from '../../urls.svelte.js';
    import { t }             from '../../translations.svelte.js';
    import { user }          from '../../user.svelte.js';

    const router = useTinyRouter();
    let users    = $state([]);

    async function listUsers(){
        const url  = 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  = 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];
        }
    }

    onMount(listUsers);
</script>

<fieldset tabindex="0">
    <legend>
        {t('user_list')}
        {#if user.permissions.includes('CREATE_USERS')}
        <button onclick={() => router.navigate('/user/create')}>{t('create_new_object',{object:t('user')})}</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>