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

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

    import TypeSelector      from './TypeSelector.svelte';

    let companies       = {};
    let router          = useTinyRouter();
    let company_id      = +router.query.company_id;
    let documents       = null;
    let selected_company = null;

    function createDoc(type){
        router.navigate(`/document/add?company_id=${selected_company.id}&document_type=${type}`)
    }

    async function deleteDoc(ev,doc){
        if (confirm(t('really_delete',doc.number))){
            const url  = api(`document/${doc.id}`);
            const resp = await fetch(url,{
                credentials: 'include',
                method: 'DELETE'
            });
            if (resp.ok){
                load(selected_company); // relaod docs
            } else {
                error(resp);
            }
        }
    }

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

    async function loadCompanies(){
        const url  = api('company/list');
        const resp = await fetch(url,{ credentials: 'include'});
        if (resp.ok){
            companies = await resp.json();
            yikes();
        } else {
            error(resp);
        }
        if (company_id) {
            for (let comp of Object.values(companies)){
                if (comp.id == company_id){
                    load(comp);
                    break;
                }
            }
        }
    }


    function show(id){
        router.navigate(`/document/${id}/view`);
    }

    onMount(loadCompanies);
</script>

<svelte:head>
    <title>Umbrella – {t('documents')}</title>
</svelte:head>

<fieldset>
    <legend>{selected_company ? t( 'docs_of_company',{company:selected_company.name}) : t('document_list')}</legend>
    {#if error}
    <div class="error">{error}</div>
    {/if}
    <div>
        {t('select_company')}
        {#each Object.entries(companies) as [id,company]}
        <button onclick={() => load(company)}>{company.name}</button>
        {/each}
    </div>
    {#if documents}
    <table>
        <thead>
            <tr>
                <th>{t('number')}</th>
                <th>{t('date')}</th>
                <th>{t('customer')}</th>
                <th>{t('gross_sum')}</th>
                <th>{t('type')}</th>
                <th>{t('state')}</th>
                <th>
                    {t('actions')}
                    <TypeSelector caption={t('create_new_object',{object:t('document')})} onSelect={createDoc} />
                </th>
            </tr>
        </thead>
        <tbody>
            {#each Object.entries(documents).reverse() as [id,document]}
            <tr>
                <td onclick={() => show(id)}>{document.number}</td>
                <td onclick={() => show(id)}>{document.date}</td>
                <td onclick={() => show(id)}>{document.customer.name.split('\n')[0]}</td>
                <td onclick={() => show(id)}>{document.sum/100 + document.currency}</td>
                <td onclick={() => show(id)}>{t('type_'+document.type)}</td>
                <td onclick={() => show(id)}>{t('state_'+document.state.name)}</td>
                <td>
                    {#if document.state.id == 1}
                    <button onclick={(ev) => deleteDoc(ev,document)}>{t('delete')}</button>
                    {/if}
                </td>
            </tr>
            {/each}
        </tbody>
    </table>
    {/if}
</fieldset>
