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

    import { api }           from '../urls.svelte';
    import { t }             from '../translations.svelte';
    import { msToTime, now } from '../time.svelte';
    import { timetrack }     from '../user.svelte';

    let interval = null;
    const router  = useTinyRouter();

    async function stopTrack(){
        if (timetrack.running.id){
            const url = api(`time/${timetrack.running.id}/stop`);
            const resp = await fetch(url,{
                credentials : 'include',
                method      : 'POST',
                body        : now()
            });
            if (resp.ok){
                timetrack.stopped = await resp.json();
                timetrack.running = null;
                timetrack.elapsed = null;
                timetrack.start   = null;
                go();
            }
        }
    }

    function go(){
        router.navigate('/time');
    }

    function updateElapsed(){
        timetrack.elapsed = msToTime(Date.now() - timetrack.start);
    }

    $effect(() => {
        if (timetrack.running) {
            timetrack.start = new Date(timetrack.running.start_time*1000);
            interval = setInterval(updateElapsed,1000);
        } else {
            clearInterval(interval);
            timetrack.elapsed = null;
            interval = null;
        }
    });

    onDestroy(() => {
        if (interval) clearInterval(interval);
    });
</script>


{#if timetrack.running}
<span class="timetracking">
    <span onclick={go} >{timetrack.running.subject} {#if timetrack.elapsed}({timetrack.elapsed}){/if}</span>
    <button onclick={stopTrack} title={t('stop')} class="symbol"></button>
</span>
{/if}