<script>
    import {sortByField} from "../../edges/sortEdges";
    import Sortable from "../../libs/Sortable.svelte";
    import PreviewFile from "../previews/PreviewFile.svelte";
    import Dropdown from "../../common/Dropdown.svelte";
    import Dialog from "../../dialog/Dialog.svelte";
    import {insertEdges} from "./reference.js";
    import {getContext} from "svelte";

    const channel = getContext("channel");
    export let field;
    export let record;
    export let graph
    let browseModal;
    $: references = graph?.edges
        .filter((edge) => edge.field === field.name)
        .map((edge) => {
            return graph.records.find((increc) => increc.id === edge.target && record.id === edge.source);
        }).filter((rec) => (rec?.id ? true : false)) ?? [];

    let collections = channel.schemas.filter((aschema) =>
        field.collections.includes(aschema.name)
    );

    function removeReference(e) {
        e.preventDefault();
        graph.edges = graph.edges.filter(
            (edge) => !(edge.target === e.detail && edge.field === field.name)
        );
    }

    function openBrowseModal(e, schema) {
        e.preventDefault();
        browseModal.open(schema);
    }

    async function reorder(e) {

        graph.edges = await sortByField(e.detail.source, e.detail.target, graph.edges, field.name, references);

    }

    function insert(e) {
        e.preventDefault();
        browseModal.close();
        graph = insertEdges(graph, record, e.detail.records, field.name, e.detail.action);
    }
</script>

<div class="mb-0">
    {#if field.collections.length === 1}
        <button
                class="button"
                on:click={(e) => openBrowseModal(e, collections[0].name)}
        >
            Browse
        </button>
    {:else}
        <Dropdown>
            <div slot="button">
                Browse
            </div>
            {#each collections as collection}
                <!-- {`${channelurl}/content/${collection.name}?parent=${record.id}&parentfield=${field.name}`} -->
                <a
                        class="dropdown-item"
                        on:click={(e) => openBrowseModal(e, collection.name)}
                        href="/">{collection.label}</a
                >
            {/each}
        </Dropdown>
    {/if}
</div>
{#if references.length > 0}
    <Sortable sortableClass="mt-3" on:update={reorder}>
        {#each references as reference (reference.id)}
            <PreviewFile record={reference} hasDelete={true} on:remove={removeReference}></PreviewFile>
        {/each}
    </Sortable>
{/if}
<Dialog bind:this={browseModal} on:insert={insert}></Dialog>
