<script>
    import {getContext} from "svelte";
    import {debounce} from "lodash";
    import {previewTitle} from "../Preview";

    const channel = getContext("channel");
    export let field;

    export let value;
    export let search;
    $: options = [];
    export const update = debounce((e) => {
        axios
            .get("/records/suggestions", {
                params: {
                    schema: field.optionsFrom,
                    field: field.optionsField,
                    value: search,
                    ui: field.ui,
                },
            })
            .then((response) => {
                options = response.data;
            })
            .catch((error) => {
                console.log(error);
            });
    }, 500);

    function select(e, option) {
        e.preventDefault();
        value = option.data[field.optionsField];
        search = "";
    }
</script>

{#if field.optionsFrom}
    {#each options as option (option.id)}
        <div
                on:click={(e) => select(e, option)}
                on:keypress={(e) => select(e, option)}
        >
            <span class="dropdown-item">
                {previewTitle(channel.schemas, option)}
                <small class="text-muted "
                >{option.data[field.optionsField]}</small
                >
            </span>
        </div>
    {:else}
        {#if search && field.optionsSuggest}
            <div
                on:click={(e) => {
                    value = search;
                    search = "";
                }}
                on:keypress={(e) => {
                    value = search;
                    search = "";
                }}
            >
                <span class="dropdown-item">
                    Add "{search}"
                </span>
            </div>
        {:else}
            No results
        {/if}
    {/each}
{/if}
