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

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

    let {
        company_id,
        hide = {},
        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 post(url,data);
        if (resp.ok){
            projects = await resp.json();
            yikes();
        } else {
            error(resp);
        }
    }

    function filter(newTimes, excluded_ids){
        times = newTimes.filter(time => !excluded_ids.includes(time.id));
    }

    async function loadTimes(projectId){
        const url = api('time/list');
        let data = { company_id: company_id, project_id: projectId };
        const resp = await post(url,data);
        if (resp.ok){
            yikes();
            let newTimes = await resp.json();
            let present_times = Object.values(hide).filter(pos => pos.time_id).map(pos => pos.time_id)
            filter(newTimes,present_times);
        } else error(resp);
    }

    function select(time){
        filter(times,[time.id]);
        onSelect(time);
    }

    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={() => select(time)}>
        <span class="duration">{(time.duration).toFixed(3)} {t('hours')}</span>
        <span class="subject">{time.subject}</span>
        <span class="start_time">{new Date(time.start_time*1000).toUTCString()}</span>
        <span class="description">{@html target(time.description.rendered)}</span>
    </div>
<hr/>
    {/each}
    {/if}
</div>
