<script>
    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);
    }

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

<div class="mb-3">
    <label class="mt-4 mb-3">Rich editor files</label>
    {#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}
    {#each references as reference (reference.id)}
        <!--This div helps the sorting thing-->
        <div>
            <PreviewFile record={reference} hasDelete={true} hasInsert={true} on:remove={removeReference}
                         on:editor-insert></PreviewFile>
        </div>
    {/each}
{/if}
<Dialog bind:this={browseModal} on:insert={insert}></Dialog>
