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

    import Autocomplete from '../../Components/Autocomplete.svelte';

    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'

    let {
        id        = null,
        getCandidates = getCandidateTags,
        module,
        onEmptyCommit = () => {},
        tags      = $bindable([]),
        user_list = [],
    } = $props();
    let router = useTinyRouter();

    async function addTag(newTag){
        if (!newTag) return;
        if (!id) {
            // when creating elements, they don`t have an id, yet
            tags.push(newTag);
            tags = tags.sort();
            newTag = '';
            return;
        }
        const url = api(`tags/${module}/${id}`);
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'POST',
            body        : JSON.stringify({tag:newTag,user_list:user_list})
        });
        if (resp.ok){
            newTag = await resp.text();
            tags.push(newTag);
            tags  = tags.sort();
            yikes();
            newTag = '';
        } else {
            error(resp);
        }
        return false;
    }

    async function drop(tag){
        if (!id){ // then creating new elements, the don`t have an id, yet
            tags = tags.filter(item => item !== tag);
            return;
        }
        const url = api(`tags/${module}/${id}`);
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'DELETE',
            body        : tag
        });
        if (resp.ok){
            tag  = await resp.text();
            tags = tags.filter(item => item !== tag);
        } else {
            error(resp);
        }
        return false;
    }

    async function getCandidateTags(input){
        if (!input || input.length <3) return [];
        const url = api(`tags/search/${encodeURI(input)}`);
        const res = await get(url);
        if (res.ok){
            yikes();
            const list = await res.json();
            return list.map(elem => {return {display:elem}});
        } else error(res);
    }

    async function loadTags(entityId){
        if (!entityId) return; // when crating elements, they dont`t have an id, yet.
        const url  = api(`tags/${module}/${entityId}`);
        const resp = await get(url);
        if (resp.ok) {
            tags = await resp.json();
            tags = tags.sort();
        } else {
            error(resp);
        }
    }

    async function onCommit(wrapped){
        if (!wrapped.display) {
            onEmptyCommit();
        } else addTag(wrapped.display.trim());
    }

    function onSelect(dummy){}

    function show(tag){
        router.navigate(`/tags/use/${tag}`);
    }


    $effect(() => loadTags(id));
</script>

<div class="taglist">
    {#each tags as tag,idx}
    <span class="tag">
        <span onclick={() => show(tag)}>{tag}</span>&nbsp;<button onclick={() => drop(tag)} class="symbol"></button>
    </span>
    {/each}
    <span class="tag editor">
        <Autocomplete {getCandidates} {onCommit} {onSelect} id="new_tag_input" />
    </span>
</div>
