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

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

    let caption         = $state(t('save_service'));
    let disabled        = $state(false);
    let service         = $state({})
    let { serviceName } = $props();
    let message         = $state(t('loading_data'));
    let router          = useTinyRouter();

    onMount(async () => {
        const url  = api(`user/oidc/${serviceName}`);
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            const json = await resp.json();
            for (let key of Object.keys(json)) service[key] = json[key];
        } else {
            message = await resp.text();
            if (!message) message = t(resp);
        }
    });

    async function update(){
        caption    = t('data_sent');
        const url  = api(`user/oidc/${serviceName}`);
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'PATCH',
            body        : JSON.stringify(service)
        });
        if (resp.ok){
            caption = t('saved');
            router.navigate('/user');
        } else {
            caption = await resp.text();
            if (!caption) caption = t(resp);
        }
    }
</script>

<fieldset>
    <legend>{t('edit_service',{name:(serviceName||"")})}</legend>
    {#if service.name || !serviceName}
    <table>
        <tbody>
            <tr>
                <th>{t('name')}</th>
                <td>
                    <input type="text" bind:value={service.name} />
                </td>
            </tr>
            <tr>
                <th>{t('client_id')}</th>
                <td>
                    <input type="text" bind:value={service.client_id} />
                </td>
            </tr>
            <tr>
                <th>{t('client_secret')}</th>
                <td>
                    <input type="text" bind:value={service.client_secret} />
                </td>
            </tr>
            <tr>
                <th>{t('base_url')}</th>
                <td>
                    <input type="text" bind:value={service.url} />
                </td>
            </tr>
        </tbody>
    </table>
    <button onclick={update} {disabled}>{caption}</button>
    <button onclick={() => router.navigate('/user')} {disabled}>{t('abort')}</button>
    {:else}
    {message}
    {/if}
</fieldset>