<script>
    import { api } from '../../urls.svelte';
    import { error, yikes } from '../../warn.svelte';
    import { name }   from '../../vcard.js';
    import { t }   from '../../translations.svelte';


    import Address from './Address.svelte';
    import Email from './Email.svelte';
    import ExtraField from './ExtraField.svelte';
    import FN from './FN.svelte';
    import Name from './Name.svelte';
    import Number from './Number.svelte';
    import Org from './Org.svelte';
    import URL from './URL.svelte';

    let { contact } = $props();

    let addresses = $derived(contact.vcard.match(/^ADR.*:.+$/gm));
    let code = $state(false);
    let emails = $derived(contact.vcard.match(/^EMAIL.*:.+$/gm));
    let extra_fields = $derived(contact.vcard.match(/^X-.*:.+/gm));
    let fns = $derived(contact.vcard.match(/^FN.*:.+$/gm));
    let names = $derived(contact.vcard.match(/^N.*:.+$/gm));
    let numbers = $derived(contact.vcard.match(/^TEL.*:.+$/gm));
    let orgs = $derived(contact.vcard.match(/^ORG.*:.+$/gm));
    let urls = $derived(contact.vcard.match(/^URL.*:.+$/gm));

    function add_address(){
        var new_addr = `ADR;TYPE=WORK:;;${t('street')};${t('locality')};${t('region')};${t('post_code')};${t('country')}`;
        patch('END:',`${new_addr}\nEND:`);
    }

    function add_email(){
        patch('END:',`EMAIL:${t('email')}@example.com\nEND:`);
    }

    function add_number(){
        patch('END:',`TEL:${t('phone')}\nEND:`);
    }

    function add_url(){
        patch('END:',`URL:https://example.com\nEND:`);
    }

    async function drop(){
        for (let n of names){
            n = name(n);
            n = (n.given + ' ' + n.family).trim();
            if (confirm(t('confirm_delete',{element:n}))) break;
            return
        }
        const url = api(`contact/${contact.id}`);
        const res = await fetch(url,{
            credentials:'include',
            method:'DELETE'
        });
        if (res.ok){
            yikes();
            contact = null;
        } else {
            error(res);
        }
    }

    async function patch(from,to){
        if (from == to) return;
        const newContact = contact.id == 0;
        const url = api(newContact ? 'contact' : `contact/${contact.id}`);
        const changeset = JSON.stringify({ from: from, to: to });
        const res = await fetch(url,{
            method: newContact ? 'POST' : 'PATCH',
            credentials:'include',
            body: newContact  ? contact.vcard.replace(from,to) :  changeset
        });
        if (res.ok){
            yikes();
            contact = await res.json();
        } else {
            error(res);
        }
        return true;
    }

    function toggleCode(){
        code = !code;
    }
</script>

{#if contact}
<fieldset class="vcard">
    <legend>
        {#if contact.id}
        {t('contact_number',{number:contact.id})}
        {:else}
        {t('new_contact')}
        {/if}
        <button class="symbol" onclick={toggleCode}></button>
        {#if contact.id}
        <button class="symbol" onclick={drop}></button>
        {/if}
    </legend>
    <table>
        <thead></thead>
        <tbody>
            <tr>
                <td>
                    {#each fns as code}
                    <FN {code} {patch} />
                    {/each}
                </td>
                {#if code}
                <td rowspan="6">
                    <pre>{contact.vcard}</pre>
                </td>
                {/if}
            </tr>
            <tr>
                <td>
                    {#each orgs as code}
                    <Org {code} {patch} />
                    {/each}
                </td>
            </tr>
            <tr>
                <td>
                    {#each names as code}
                    <Name {code} {patch} />
                    {/each}
                </td>
            </tr>
            <tr>
                <td>
                    <button class="symbol" onclick={add_address} title={t('add_object',{object:t('address')})}></button>
                    {#each addresses as code}
                    <Address {code} {patch} />
                    {/each}
                </td>
            </tr>
            <tr>
                <td class="phones">
                    <button class="symbol" onclick={add_number} title={t('add_object',{object:t('number')})}></button>
                    {#each numbers as code}
                    <Number {code} {patch} />
                    {/each}
                </td>
            </tr>
            <tr>
                <td>
                    <button class="symbol" onclick={add_email} title={t('add_object',{object:t('email')})}></button>
                    {#each emails as code}
                    <Email {code} {patch} />
                    {/each}
                </td>
            </tr>
            <tr>
                <td>
                    {#each extra_fields as code}
                    <ExtraField {code} {patch} />
                    {/each}
                </td>
            </tr>
            <tr>
                <td>
                    <button class="symbol" onclick={add_url} title={t('add_object',{object:t('website')})}></button>
                    {#each urls as code}
                    <URL {code} {patch} />
                    {/each}
                </td>
            </tr>
        </tbody>
    </table>
</fieldset>
{/if}