<script>
    import {getContext} from "svelte";
    import {insertEdges} from "./reference";
    import PreviewCard from "../PreviewCard.svelte";
    import {getErrorMessage} from "./errorMessage";
    import {sortByField} from "../../edges/sortEdges";
    import ReferenceInlineButtons from "./ReferenceInlineButtons.svelte";
    import Sortable from "../../libs/Sortable.svelte";

    const channel = getContext("channel");
    export let record;
    export let field;
    export let graph;
    export let validationErrors;
    $: errorMessage = getErrorMessage(validationErrors, field.name);

    $: currentReferences  = graph._children[field.name] ?? [];

    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 reorder(e) {
        graph.edges = sortByField(e.detail.source, e.detail.target, graph.edges, field.name);
    }

    function insert(e) {
        e.preventDefault();
        graph = insertEdges(graph,record,e.detail.records,field.name,e.detail.action);
    }

</script>

{#if errorMessage}
    <div class="invalid-feedback d-block mb-3">
        {errorMessage}
    </div>
{/if}
<div class="inline-card-wrapper">
    <ReferenceInlineButtons
        buttonClass="mt-2"
        recordId={null}
        schemas={collections}
        on:insert={insert}
        on:save={insert}
    />
</div>
{#if currentReferences.length > 0}
    <Sortable sortableClass="row row-cols-3 mt-3" on:update={reorder}>
        {#each currentReferences as reference (reference.id)}
            <div class="col mb-3">
                <PreviewCard
                    classes="h-100"
                    record={reference}
                    hasDelete={true}
                    on:remove={removeReference}
                />
            </div>
        {/each}
    </Sortable>
{/if}
