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

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

    import MarkdownEditor    from '../../Components/MarkdownEditor.svelte';
    import PermissionEditor  from '../../Components/PermissionEditor.svelte';
    import Tags              from '../tags/TagList.svelte';

    let { assignee = null, on_abort = null, project_id = null, parent_task_id = null, state_id = null } = $props();
    let project          = $state(null);
    let extendedSettings = $state(false);
    let parent_task      = $state(null);
    let task = $state({
        name           : '',
        description    : { source:'',rendered:''},
        due_date       : null,
        est_time       : null,
        members        : {},
        no_index       : false,
        show_closed    : false,
        start_date     : null,
        tags           : []
    });
    let router = useTinyRouter();

    function addMember(member){
        let uid = member.id;
        task.members[uid] = project.members[uid];
    }

    function flat(json){
        return JSON.parse(JSON.stringify(json));
    }

    function dropMember(member){
        delete task.members[member.user.id];
        console.log({drop:member.user.id});
        ///  TODO: ?
    }

    async function getCandidates(text){
        const origin = parent_task ? parent_task.members : project.members;
        return Object.values(origin)
            .filter(member => member.user.name.toLowerCase().includes(text.toLowerCase()))
            .map(member => {return { ...member.user,display:member.user.name}});
    }

    async function load(){
        if (parent_task_id) await loadParent();
        if (project_id) loadProject();
        if (state_id)   task.status   = { code : +state_id };
        loadTags();
    }

    async function loadParent(){
        const url  = api(`task/${parent_task_id}`);
        const resp = await get(url);
        if (resp.ok){
            parent_task         = await resp.json();
            task.parent_task_id = +parent_task_id;
            project_id          = +parent_task.project_id;
            yikes();
            project             = null; // TODO
        } else error(resp);
    }

    async function loadProject(){
        const url  = api(`project/${project_id}`);
        const resp = await get(url);
        if (resp.ok){
            project           = await resp.json();
            task.project_id   = +project_id;
            if (assignee && project.members[assignee]){
                task.members[assignee] = project.members[assignee];
                task.members[assignee].permission = { name : "ASSIGNEE", code : 3 }
            }
            if (task.taks.length < 1) task.tags = project.tags;
            yikes();
        } else {
            error(resp);
        }
    }

    async function loadTags(){
        let url = null;
        if (project_id) url = api(`tags/project/${project_id}`);
        if (parent_task_id) url = api(`tags/task/${parent_task_id}`);
        if (url) {
            const resp = await get(url);
            if (resp.ok) task.tags = await resp.json();
        }
    }

     function onkeydown(e){
        if (e.ctrlKey && e.keyCode === 83) {
            e.preventDefault();
            saveTask();
        }
    }

    async function saveTask(){
        const url  = api('task/add');
        const resp = await post(url,task);
        if (resp.ok) {
            localStorage.removeItem(`task/${task.id}/description`);
            if (!assignee) { // if assignee is set, this form was opened within an external context. hence we don`t want to navigate somewhere else!
                task = await resp.json();
                if (task.parent_task_id){
                    router.navigate(`/task/${task.parent_task_id}/view`);
                } else router.navigate(`/task/${task.id}/view`);
            }
            yikes();
        } else {
            error(resp);
        }
    }

    function toggleSettings(){
        extendedSettings = !extendedSettings;
    }

    onMount(load);
</script>

<svelte:head>
    <title>Umbrella – {t('add_object',{object:t('task')})}</title>
</svelte:head>

<fieldset>
    <legend>{t('add_object',{object:t('task')})}</legend>
    <div class="task grid2">
        <div>{t('name')}</div>
        <div>
            <input bind:value={task.name} autofocus>
        </div>

        {#if project}
        <div>{t('project')}</div>
        <a href="/project/{project.id}/view">{project.name}</a>
        {/if}

        {#if parent_task}
        <div>{t('parent_task')}</div>
        <div>{parent_task.name}</div>
        {/if}

        <div>{t('description')}</div>
        <div>
            <MarkdownEditor bind:value={task.description} simple={true} store_id="task/add_to/{project_id}"/>
        </div>
        <div>{t('tags')}</div>
        <div>
            <Tags module={null} bind:tags={task.tags} onEmptyCommit={saveTask} />
        </div>

        {#if extendedSettings}
        <div>{t('members')}</div>
        <div>
            <PermissionEditor members={task.members} {addMember} {dropMember} {getCandidates} />
        </div>

        <div>{t('estimated_time')}</div>
        <div>
            <input type="number" bind:value={task.est_time} /> {t('hours')}
        </div>

        <div>{t('start_date')}</div>
        <div>
            <input type="date" bind:value={task.start_date} />
        </div>

        <div>{t('due_date')}</div>
        <div>
            <input type="date" bind:value={task.due_date} />
        </div>

        <div>{t('subtasks')}</div>
        <div>
            <label>
                <input type="checkbox" bind:checked={task.show_closed} >
                {t('display_closed_tasks')}
            </label>
        </div>

        <div>
            {t('index_page')}
        </div>
        <label>
            <input type="checkbox" bind:checked={task.no_index} >
            {t('hide_on_index_page')}
        </label>
        {:else}
        <div>{t('extended_settings')}</div>
        <div>
            <button onclick={toggleSettings}>{t('show')}</button>
        </div>
        {/if}
    </div>
    <button onclick={saveTask}>{t('save_object',{object:t('task')})}</button>
    {#if on_abort}
    <button onclick={on_abort}>{t('abort')}</button>
    {/if}
</fieldset>
