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

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

    const router = useTinyRouter();

    let connections = $state({});
    let services = $state([]);

    async function connect(service){
        const url  = api(`user/oidc/redirect/${service}`);
        const resp = await get(url);
        if (resp.ok){
            var json = await resp.json();
            if (json.authorization_endpoint) {
                var endpoint = json.authorization_endpoint;
                delete json.authorization_endpoint;
                location.href = endpoint + '?' + new URLSearchParams(json);
            }
        }
    }

    async function dropConn(service){
        const url = api(`user/oidc/${service}`);
        const resp = await drop(url);
        if (resp.ok) loadConnections();
    }

    async function load(){
        await loadButtons();
        loadConnections();
    }

    async function loadButtons(){
        const url  = api(`user/oidc/buttons`);
        const resp = await get(url);
        if (resp.ok) services = await resp.json();
    }

    async function loadConnections(){
        const url  = api('user/oidc/connected');
        const resp = await get(url);
        if (resp.ok) {
            const json = await resp.json();
            connections = {};
            for (let conn of json) connections[conn.service_id] = conn;
        }
    }

    async function unlink(connection){
        const url  = api('user/oidc/connected');
        const resp = await fetch(url,{
            method      : 'DELETE',
            credentials : 'include',
            body        : JSON.stringify(connection)
        });
        if (resp.ok){
            loadConnections();
        } else {
            alert('failed');
        }
    }

    onMount(load);
</script>

<fieldset tabindex="0">
    <legend>
        {t('login_services')}
        {#if user.permissions.includes('MANAGE_LOGIN_SERVICES')}
        <button onclick={() => router.navigate('/user/oidc/add')}>{t('add_login_service')}</button>
        {/if}
    </legend>
    <table>
        <thead>
            <tr>
                <th>{t('service')}</th>
                <th>{t('foreign_id')}</th>
                <th>{t('actions')}</th>
            </tr>
        </thead>
        <tbody>
        {#each services as service,i}
            <tr>
                <td>{service}</td>
                {#if connections[service]}
                <td>
                    {connections[service].foreign_id}
                </td>
                <td>
                    <button onclick={() => unlink(connections[service])}>{t('unlink')}</button>
                </td>
                {:else}
                <td></td>
                <td>
                    <button onclick={() => connect(service)}>{t('connect_service')}</button>
                    {#if user.permissions.includes('MANAGE_LOGIN_SERVICES')}
                    <button onclick={() => router.navigate(`/user/oidc/edit/${service}`)}>{t('edit')}</button>
                    <button onclick={() => dropConn(service)}>{t('delete')}</button>
                    {/if}
                </td>
                {/if}
            </tr>
        {/each}
        </tbody>
    </table>
</fieldset>