<script>
    import { onMount }        from 'svelte';

    import { api, get, post }            from '../urls.svelte';
    import { t }              from '../translations.svelte';
    import { error, yikes } from '../warn.svelte';

    import Autocomplete       from './Autocomplete.svelte';
    import PermissionSelector from './PermissionSelector.svelte';

    let {
        addMember        = (entry)    => console.log(`no handler for addMember(${entry})`),
        dropMember       = (member)   => console.log(`no handler for dropMember(${member})`),
        getCandidates    = defaultGetCandidates,
        members,
        updatePermission = (uid,perm) => console.log(`no handler for updatePermission(${uid}, ${perm})`)
    } = $props();

    let permissions   = $state(null);
    let sortedMembers = $derived.by(() => Object.values(members).sort((a, b) => a.user.name.localeCompare(b.user.name)));

    async function defaultGetCandidates(text){
        const url  = api('user/search');
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'POST',
            body        : text
        });
        if (resp.ok){
            var json = await resp.json();
            return Object.values(json).map(user => { return {...user,display:user.name}; });
        } else {
            return [];
        }
    }

    async function loadPermissions(){
        const url  = api('task/permissions');
        const resp = await get(url);
        if (resp.ok){
            permissions = await resp.json();
        } else error(resp);
    }

    onMount(loadPermissions);
</script>

<table>
    <tbody>
    {#each sortedMembers as member (member.user.id)}
    <tr>
        <td>{member.user.name}</td>
        <td>
            <PermissionSelector {permissions} selected={member.permission.code} onchange={(perm) => updatePermission(member.user.id,perm)} />
            {#if member.permission.name != 'OWNER'}
            <button onclick={() => dropMember(member)}>x</button>
            {/if}
        </td>
    </tr>
    {/each}
    <tr>
        <td>{t('add_object',{object:t('member')})}</td>
        <td>
            <Autocomplete {getCandidates} onSelect={addMember} />
        </td>
    </tr>
    </tbody>
</table>
