<script>
    import {getContext} from "svelte";
    import {uniqBy} from "lodash";
    import {sortByField} from "../../edges/sortEdges";
    import PreviewCard from "../PreviewCard.svelte";
    import Sortable from "../../libs/Sortable.svelte";
    import BrowseModal from "./BrowseModal.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);
    }

    function insert(e) {
        e.preventDefault();
        browseModal.close();
        const recordsToInsert = e.detail.records;
        const action = e.detail.action;
        let newEdges = recordsToInsert.map((r) => {
            return {
                target: r.id,
                source: record.id,
                sourceSchema: record.schema,
                targetSchema: r.schema,
                field: field.name,
                rank: ""
            };
        });

        let replacedEdges = graph.edges ?? [];
        if (action === "replace") {
            replacedEdges = replacedEdges.filter((e) => e.field !== field.name);
        }

        graph.records = uniqBy([...graph.records, ...recordsToInsert], (r) => r.id);
        graph.edges = uniqBy([...replacedEdges, ...newEdges], (e) => e.target + e.field);
    }
</script>

<div class="mb-0">
    {#if field.collections.length === 1}
        <button
            class="btn btn-outline-primary"
            on:click={(e) => openBrowseModal(e, collections[0].name)}
        >
            Browse
        </button>
    {:else}
        <div class="dropdown d-inline-block">
            <button
                class="btn btn-outline-primary btn-sm"
                type="button"
                data-bs-toggle="dropdown"
                aria-expanded="false"
            >
                Browse
            </button>
            <ul class="dropdown-menu">
                {#each collections as collection}
                    <li>
                        <!-- {`${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
                        >
                    </li>
                {/each}
            </ul>
        </div>
    {/if}
</div>
{#if references.length > 0}
    <Sortable sortableClass="row row-cols-3 mt-3" on:update={reorder}>
        {#each references as reference (reference.id)}
            <div class="col mb-3">
                <PreviewCard
                    classes="h-100"
                    record={reference}
                    hasDelete={true}
                    on:remove={removeReference}
                />
            </div>
        {/each}
    </Sortable>
{/if}
<BrowseModal bind:this={browseModal} on:insert={insert}/>
