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

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

    let {
        company_id,
        onSelect = (time) => {}
    } = $props();

    let projects = $state(null);
    let times    = $state(null);

    async function loadProjects(){
        const url  = api('project/list');
        let data   = { company_id: company_id };
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'POST',
            body        : JSON.stringify(data)
        });
        if (resp.ok){
            projects = await resp.json();
            yikes();
        } else {
            error(resp);
        }
    }

    async function loadTimes(projectId){
        const url = api('time/list');
        let data = { company_id: company_id, project_id: projectId };
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'POST',
            body        : JSON.stringify(data)
        });
        if (resp.ok){
            times = await resp.json();
        } else {
            error(resp);
        }
    }

    onMount(loadProjects);
</script>

<div>
    <h1>Times</h1>
    {#if projects}
    {#each Object.entries(projects) as [pid,project]}
    <button onclick={() => loadTimes(+pid)}>{project.name}</button>
    {/each}
    {/if}
    {#if times}
    {#each times as time,idx2}
    <div class="time" onclick={() => onSelect(time)}>
        <span class="duration">{(time.duration).toFixed(3)} {t('hours')}</span>
        <span class="subject">{time.subject}</span>
        <span class="start_time">{time.start_time}</span>
        <span class="description">{@html target(time.description.rendered)}</span>
    </div>
    {/each}
    {/if}
</div>
