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

    import {api}     from '../urls.svelte.js';
    import {addr, email, extra, fn, name, org} from '../vcard.js';
    import {t}       from '../translations.svelte.js';

    let {
        caption,
        onselect = (contact) => console.log('selected '+contact.FN||contact.ORG)
    } = $props();

    let contacts = $state(null);
    let message = t('loading');
    let value   = 0;

    async function loadContacts(){
        const url  = api('contact/list');
        const resp = await fetch(url,{ credentials: 'include'});
        if (resp.ok){
            const json = await resp.json();
            contacts = Object.values(json).map(contact => {
                contact.ADR   = addr(contact.vcard);
                contact.EMAIL = email(contact.vcard);
                contact.N     = name(contact.vcard);
                contact.FN    = fn(contact.vcard);
                contact.ORG   = org(contact.vcard);
                const extras  = contact.vcard.match(/^X-.*:.+/gm);
                if (extras) {
                    for (let ex of extras){
                        ex = extra(ex);
                        switch (ex.name){
                            case 'CUSTOMER-NUMBER':
                                contact.customer_number = ex.value;
                                break;
                            case 'TAX-NUMBER':
                                contact.tax_id = ex.value;
                                break;
                            case 'BANK-ACCOUNT':
                                contact.bank_account = ex.value;
                                break;
                            case 'COURT':
                                contact.local_court = ex.value;
                                break;
                            default:
                                console.log(ex);
                        }
                    }
                }
                delete contact.vcard;
                console.log(contact);
                return contact;
            })
        } else {
            message  = await resp.text();
        }
    }

    function select(){
        onselect(contacts[value]);
    }

    onMount(loadContacts)
</script>

{#if contacts}
<select onchange={select} bind:value>
    <option value={0}>{caption}</option>
    {#each contacts as contact,idx}
    <option value={idx}>{contact.FN||contact.ORG}</option>
    {/each}
</select>
{:else}
<span>{message}</span>
{/if}

