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

    import { api, get }           from '../../urls.svelte';
    import { error, yikes }  from '../../warn.svelte';
    import { t }             from '../../translations.svelte';

    import ContactSelector   from '../../Components/ContactSelector.svelte';

    let company = $state(null);
    let docType = $state(null);
    let router  = useTinyRouter();

    let document = $state({
        type : +router.query.document_type,
        customer : {
            name : ''
        },
        sender : {
            name    : 'sender',
            company : +router.query.company_id
        }
    });

    async function loadCompanies(){
        const url  = api('company/list');
        const resp = await fetch(url,{ credentials: 'include'});
        if (resp.ok){
            const companies      = await resp.json();
            company              = companies[document.sender.company];
            document.sender.name = '';
            if (company.name)         document.sender.name        += company.name+"\n";
            if (company.address)      document.sender.name        += company.address+"\n";
            if (company.tax_number)   document.sender.tax_id       = company.tax_number;
            if (company.bank_account) document.sender.bank_account = company.bank_account;
            if (company.court)        document.sender.court        = company.court;
        } else {
            error(resp);
        }
    }

    async function loadDocType(){
        const url  = api('document/types');
        const resp = await fetch(url,{ credentials: 'include'});
        if (resp.ok){
            const types = await resp.json();
            docType     = t('type_'+types[document.type]);
        } else {
            error(resp);
        }
    }

    function load(){
        yikes();
        loadCompanies();
        loadDocType();
    }

    function contactSelected(contact){
        var addr = '';
        if (contact.ORG) addr += contact.ORG.trim()+"\n";
        if (contact.N) {
            var name  = (contact.N.given+" "+contact.N.family).trim()+"\n";
            if (name != addr) addr += name;
        }
        if (contact.ADR.street)   addr += contact.ADR.street+"\n";
        if (contact.ADR.locality) addr += contact.ADR.post_code + " "+ contact.ADR.locality + "\n";
        if (contact.ADR.county)   addr += contact.ADR.country+"\n";
        document.customer.name       = addr;
        document.customer.tax_id     = contact.tax_id;
        document.customer.id         = contact.customer_number;
        document.customer.email      = contact.EMAIL;
        document.customer.contact_id = contact.id;
        if (!document.customer.id) requestNewCustomerId();
    }

    async function requestNewCustomerId(){
        var url = api(`company/${document.sender.company}/next_customer_number`);
        var res = await get(url);
            yikes();
            document.customer.id = await res.text();
        if (res.ok){
        } else error(res);
    }

    async function submit(){
        const url = api('document');
        const resp = await fetch(url,{
            method     : 'POST',
            credentials: 'include',
            body       : JSON.stringify(document)
        });
        if (resp.ok){
            const json = await resp.json();
            router.navigate(`/document/${json.id}/view`);
        } else {
            error(resp);
        }
    }

    onMount(load);
</script>

<style>
    label{display:block}
</style>

<fieldset>
    {#if docType}
    <legend>{t('add_object',{object:docType})}</legend>
    {/if}
    {#if company}
    {t('company')}: {company.name}
    <fieldset>
        <legend>{t('customer')}</legend>
        <ContactSelector caption={t('select_customer')} onselect={contactSelected} />
        <label>
            <textarea bind:value={document.customer.name}></textarea>
            {t('customer_address')}
        </label>
        <label>
            <input bind:value={document.customer.tax_id} />
            {t('tax_id')}
        </label>
        <label>
            <input bind:value={document.customer.id} />
            {t('customer_id')}
        </label>
        <label>
            <input bind:value={document.customer.email} />
            {t('email')}
        </label>
    </fieldset>
    {/if}
    <fieldset>
        <legend>{t('sender')}</legend>
        <label>
            <textarea bind:value={document.sender.name}></textarea>
            {t('sender_name')}
        </label>
        <label>
            <input bind:value={document.sender.tax_id} />
            {t('sender_tax_id')}
        </label>
        <label>
            <textarea bind:value={document.sender.bank_account}></textarea>
            {t('sender_bank_account')}
        </label>
        <label>
            <input bind:value={document.sender.court} />
            {t('sender_local_court')}
        </label>
    </fieldset>
    <button onclick={submit}>{t('create_new_object',{object:docType})}</button>
</fieldset>
