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

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

    let {
        caption,
        company,
        value = $bindable(0),
        onchange = () => console.log('changed')
    } = $props();

    let message   = t('loading');
    let templates = $state(null);

    async function loadTemplates(){
        const url = api('document/templates');
        var resp = await fetch(url,{
            credentials : 'include',
            method      : 'POST',
            body        : JSON.stringify({company:company})
        });
        if (resp.ok){
            templates = await resp.json();
        } else {
            message   = await resp.text();
        }
    }

    onMount(loadTemplates)
</script>

{#if templates}
<select bind:value onchange={onchange}>
    <option value={0}>{caption}</option>
    {#each Object.entries(templates) as [id,template]}
    <option value={template.id}>{template.name}</option>
    {/each}
</select>
{:else}
<span>{message}</span>
{/if}

